Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1 | \section{\module{optparse} --- More powerful command line option parser} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 2 | \declaremodule{standard}{optparse} |
| 3 | \moduleauthor{Greg Ward}{gward@python.net} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 4 | \modulesynopsis{More convenient, flexible, and powerful command-line parsing library.} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 5 | \versionadded{2.3} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 6 | \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 Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 9 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 10 | \code{optparse} is a more convenient, flexible, and powerful library for |
| 11 | parsing command-line options than \code{getopt}. \code{optparse} uses a more |
| 12 | declarative 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 |
| 15 | syntax, and additionally generates usage and help messages for you. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 16 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 17 | Here's an example of using \code{optparse} in a simple script: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 18 | \begin{verbatim} |
| 19 | from optparse import OptionParser |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 20 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 21 | parser = OptionParser() |
| 22 | parser.add_option("-f", "--file", dest="filename", |
| 23 | help="write report to FILE", metavar="FILE") |
| 24 | parser.add_option("-q", "--quiet", |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 25 | action="store_false", dest="verbose", default=True, |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 26 | help="don't print status messages to stdout") |
| 27 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 28 | (options, args) = parser.parse_args() |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 29 | \end{verbatim} |
| 30 | |
| 31 | With these few lines of code, users of your script can now do the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 32 | ``usual thing'' on the command-line, for example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 33 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 34 | <yourscript> --file=outfile -q |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 35 | \end{verbatim} |
| 36 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 37 | As it parses the command line, \code{optparse} sets attributes of the |
| 38 | \var{options} object returned by \method{parse{\_}args()} based on user-supplied |
| 39 | command-line values. When \method{parse{\_}args()} returns from parsing this |
| 40 | command line, \var{options.filename} will be \code{"outfile"} and |
| 41 | \code{options.verbose} will be \code{False}. \code{optparse} supports both long |
| 42 | and short options, allows short options to be merged together, and |
| 43 | allows options to be associated with their arguments in a variety of |
| 44 | ways. Thus, the following command lines are all equivalent to the above |
| 45 | example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 46 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 47 | <yourscript> -f outfile --quiet |
| 48 | <yourscript> --quiet --file outfile |
| 49 | <yourscript> -q -foutfile |
| 50 | <yourscript> -qfoutfile |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 51 | \end{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 52 | |
| 53 | Additionally, users can run one of |
| 54 | \begin{verbatim} |
| 55 | <yourscript> -h |
| 56 | <yourscript> --help |
| 57 | \end{verbatim} |
| 58 | |
| 59 | and \code{optparse} will print out a brief summary of your script's |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 60 | options: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 61 | \begin{verbatim} |
| 62 | usage: <yourscript> [options] |
| 63 | |
| 64 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 65 | -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 Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 68 | \end{verbatim} |
| 69 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 70 | where the value of \emph{yourscript} is determined at runtime (normally |
| 71 | from \code{sys.argv{[}0]}). |
| 72 | % $Id$ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 73 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 74 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 75 | \subsection{Background\label{optparse-background}} |
| 76 | |
| 77 | \module{optparse} was explicitly designed to encourage the creation of programs with |
| 78 | straightforward, conventional command-line interfaces. To that end, it |
| 79 | supports only the most common command-line syntax and semantics |
| 80 | conventionally used under \UNIX{}. If you are unfamiliar with these |
| 81 | conventions, read this section to acquaint yourself with them. |
| 82 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 83 | |
| 84 | \subsubsection{Terminology\label{optparse-terminology}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 85 | \begin{description} |
| 86 | \item[argument] |
| 87 | a 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 |
| 90 | executed). \UNIX{} shells also use the term ``word''. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 91 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 92 | It is occasionally desirable to substitute an argument list other |
| 93 | than \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 ] |
| 97 | an argument used to supply extra information to guide or customize the |
| 98 | execution of a program. There are many different syntaxes for |
| 99 | options; the traditional \UNIX{} syntax is a hyphen (``-'') followed by a |
| 100 | single letter, e.g. \code{"-x"} or \code{"-F"}. Also, traditional \UNIX{} |
| 101 | syntax allows multiple options to be merged into a single argument, |
| 102 | e.g. \code{"-x -F"} is equivalent to \code{"-xF"}. The GNU project |
| 103 | introduced \code{"-{}-"} followed by a series of hyphen-separated words, |
| 104 | e.g. \code{"-{}-file"} or \code{"-{}-dry-run"}. These are the only two option |
| 105 | syntaxes provided by \module{optparse}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 106 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 107 | Some other option syntaxes that the world has seen include: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 108 | \begin{itemize} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 109 | \item {} |
| 110 | a 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 {} |
| 114 | a hyphen followed by a whole word, e.g. \code{"-file"} (this is |
| 115 | technically equivalent to the previous syntax, but they aren't |
| 116 | usually seen in the same program) |
| 117 | |
| 118 | \item {} |
| 119 | a plus sign followed by a single letter, or a few letters, |
| 120 | or a word, e.g. \code{"+f"}, \code{"+rgb"} |
| 121 | |
| 122 | \item {} |
| 123 | a slash followed by a letter, or a few letters, or a word, e.g. |
| 124 | \code{"/f"}, \code{"/file"} |
| 125 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 126 | \end{itemize} |
| 127 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 128 | These option syntaxes are not supported by \module{optparse}, and they never will |
| 129 | be. This is deliberate: the first three are non-standard on any |
| 130 | environment, and the last only makes sense if you're exclusively |
| 131 | targeting VMS, MS-DOS, and/or Windows. |
| 132 | \item[option argument] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 133 | an argument that follows an option, is closely associated with that |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 134 | option, and is consumed from the argument list when that option is. |
| 135 | With \module{optparse}, option arguments may either be in a separate argument |
| 136 | from their option: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 137 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 138 | -f foo |
| 139 | --file foo |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 140 | \end{verbatim} |
| 141 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 142 | or included in the same argument: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 143 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 144 | -ffoo |
| 145 | --file=foo |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 146 | \end{verbatim} |
| 147 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 148 | Typically, a given option either takes an argument or it doesn't. |
| 149 | Lots of people want an ``optional option arguments'' feature, meaning |
| 150 | that some options will take an argument if they see it, and won't if |
| 151 | they don't. This is somewhat controversial, because it makes parsing |
| 152 | ambiguous: if \code{"-a"} takes an optional argument and \code{"-b"} is |
| 153 | another option entirely, how do we interpret \code{"-ab"}? Because of |
| 154 | this ambiguity, \module{optparse} does not support this feature. |
| 155 | \item[positional argument] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 156 | something leftover in the argument list after options have been |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 157 | parsed, i.e. after options and their arguments have been parsed and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 158 | removed from the argument list. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 159 | \item[required option] |
| 160 | an option that must be supplied on the command-line; note that the |
| 161 | phrase ``required option'' is self-contradictory in English. \module{optparse} |
| 162 | doesn't prevent you from implementing required options, but doesn't |
| 163 | give 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 |
| 165 | ways to implement required options with \module{optparse}. |
| 166 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 167 | |
| 168 | For example, consider this hypothetical command-line: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 169 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 170 | prog -v --report /tmp/report.txt foo bar |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 171 | \end{verbatim} |
| 172 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 173 | \code{"-v"} and \code{"-{}-report"} are both options. Assuming that |
| 174 | \longprogramopt{report} takes one argument, \code{"/tmp/report.txt"} is an option |
| 175 | argument. \code{"foo"} and \code{"bar"} are positional arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 176 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 177 | |
| 178 | \subsubsection{What are options for?\label{optparse-what-are-options-for?}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 179 | |
| 180 | Options are used to provide extra information to tune or customize the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 181 | execution 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 |
| 183 | whatsoever. (Pick a random program from the \UNIX{} or GNU toolsets. Can |
| 184 | it run without any options at all and still make sense? The main |
| 185 | exceptions are \code{find}, \code{tar}, and \code{dd}{---}all of which are mutant |
| 186 | oddballs that have been rightly criticized for their non-standard syntax |
| 187 | and confusing interfaces.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 188 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 189 | Lots of people want their programs to have ``required options''. Think |
| 190 | about it. If it's required, then it's \emph{not optional}! If there is a |
| 191 | piece of information that your program absolutely requires in order to |
| 192 | run successfully, that's what positional arguments are for. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 193 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 194 | As 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 |
| 196 | copy files without supplying a destination and at least one source. |
| 197 | Hence, \code{cp} fails if you run it with no arguments. However, it has a |
| 198 | flexible, useful syntax that does not require any options at all: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 199 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 200 | cp SOURCE DEST |
| 201 | cp SOURCE ... DEST-DIR |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 202 | \end{verbatim} |
| 203 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 204 | You can get pretty far with just that. Most \code{cp} implementations |
| 205 | provide a bunch of options to tweak exactly how the files are copied: |
| 206 | you can preserve mode and modification time, avoid following symlinks, |
| 207 | ask before clobbering existing files, etc. But none of this distracts |
| 208 | from the core mission of \code{cp}, which is to copy either one file to |
| 209 | another, or several files to another directory. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 210 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 211 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 212 | \subsubsection{What are positional arguments for?\label{optparse-what-are-positional-arguments-for?}} |
| 213 | |
| 214 | Positional arguments are for those pieces of information that your |
| 215 | program absolutely, positively requires to run. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 216 | |
| 217 | A good user interface should have as few absolute requirements as |
| 218 | possible. If your program requires 17 distinct pieces of information in |
| 219 | order to run successfully, it doesn't much matter \emph{how} you get that |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 220 | information from the user{---}most people will give up and walk away |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 221 | before they successfully run the program. This applies whether the user |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 222 | interface is a command-line, a configuration file, or a GUI: if you make |
| 223 | that many demands on your users, most of them will simply give up. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 224 | |
| 225 | In short, try to minimize the amount of information that users are |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 226 | absolutely required to supply{---}use sensible defaults whenever |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 227 | possible. Of course, you also want to make your programs reasonably |
| 228 | flexible. That's what options are for. Again, it doesn't matter if |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 229 | they are entries in a config file, widgets in the ``Preferences'' dialog |
| 230 | of a GUI, or command-line options{---}the more options you implement, the |
| 231 | more flexible your program is, and the more complicated its |
| 232 | implementation becomes. Too much flexibility has drawbacks as well, of |
| 233 | course; too many options can overwhelm users and make your code much |
| 234 | harder to maintain. |
| 235 | % $Id$ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 236 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 237 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 238 | \subsection{Tutorial\label{optparse-tutorial}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 239 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 240 | While \module{optparse} is quite flexible and powerful, it's also straightforward to |
| 241 | use in most cases. This section covers the code patterns that are |
| 242 | common to any \module{optparse}-based program. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 243 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 244 | First, you need to import the OptionParser class; then, early in the |
| 245 | main program, create an OptionParser instance: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 246 | \begin{verbatim} |
| 247 | from optparse import OptionParser |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 248 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 249 | parser = OptionParser() |
| 250 | \end{verbatim} |
| 251 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 252 | Then you can start defining options. The basic syntax is: |
| 253 | \begin{verbatim} |
| 254 | parser.add_option(opt_str, ..., |
| 255 | attr=value, ...) |
| 256 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 257 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 258 | Each 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 |
| 260 | expect and what to do when it encounters that option on the command |
| 261 | line. |
| 262 | |
| 263 | Typically, each option will have one short option string and one long |
| 264 | option string, e.g.: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 265 | \begin{verbatim} |
| 266 | parser.add_option("-f", "--file", ...) |
| 267 | \end{verbatim} |
| 268 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 269 | You're free to define as many short option strings and as many long |
| 270 | option strings as you like (including zero), as long as there is at |
| 271 | least one option string overall. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 272 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 273 | The option strings passed to \method{add{\_}option()} are effectively labels for |
| 274 | the option defined by that call. For brevity, we will frequently refer |
| 275 | to \emph{encountering an option} on the command line; in reality, \module{optparse} |
| 276 | encounters \emph{option strings} and looks up options from them. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 277 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 278 | Once all of your options are defined, instruct \module{optparse} to parse your |
| 279 | program's command line: |
| 280 | \begin{verbatim} |
| 281 | (options, args) = parser.parse_args() |
| 282 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 283 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 284 | (If you like, you can pass a custom argument list to \method{parse{\_}args()}, |
| 285 | but that's rarely necessary: by default it uses \code{sys.argv{[}1:]}.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 286 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 287 | \method{parse{\_}args()} returns two values: |
| 288 | \begin{itemize} |
| 289 | \item {} |
| 290 | \var{options}, an object containing values for all of your options{---}e.g. if \code{"-{}-file"} takes a single string argument, then |
| 291 | \var{options.file} will be the filename supplied by the user, or |
| 292 | \code{None} if the user did not supply that option |
| 293 | |
| 294 | \item {} |
| 295 | \var{args}, the list of positional arguments leftover after parsing |
| 296 | options |
| 297 | |
| 298 | \end{itemize} |
| 299 | |
| 300 | This tutorial section only covers the four most important option |
| 301 | attributes: \member{action}, \member{type}, \member{dest} (destination), and \member{help}. |
| 302 | Of these, \member{action} is the most fundamental. |
| 303 | |
| 304 | |
| 305 | \subsubsection{Option actions\label{optparse-option-actions}} |
| 306 | |
| 307 | Actions tell \module{optparse} what to do when it encounters an option on the |
| 308 | command line. There is a fixed set of actions hard-coded into \module{optparse}; |
| 309 | adding new actions is an advanced topic covered in section~\ref{optparse-extending}, Extending \module{optparse}. |
| 310 | Most actions tell \module{optparse} to store a value in some variable{---}for |
| 311 | example, take a string from the command line and store it in an |
| 312 | attribute of \var{options}. |
| 313 | |
| 314 | If you don't specify an option action, \module{optparse} defaults to \code{store}. |
| 315 | |
| 316 | |
| 317 | \subsubsection{The store action\label{optparse-the-store-action}} |
| 318 | |
| 319 | The most common option action is \code{store}, which tells \module{optparse} to take |
| 320 | the next argument (or the remainder of the current argument), ensure |
| 321 | that it is of the correct type, and store it to your chosen destination. |
| 322 | |
| 323 | For example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 324 | \begin{verbatim} |
| 325 | parser.add_option("-f", "--file", |
| 326 | action="store", type="string", dest="filename") |
| 327 | \end{verbatim} |
| 328 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 329 | Now let's make up a fake command line and ask \module{optparse} to parse it: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 330 | \begin{verbatim} |
| 331 | args = ["-f", "foo.txt"] |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 332 | (options, args) = parser.parse_args(args) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 333 | \end{verbatim} |
| 334 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 335 | When \module{optparse} sees the option string \code{"-f"}, it consumes the next |
| 336 | argument, \code{"foo.txt"}, and stores it in \var{options.filename}. So, |
| 337 | after this call to \method{parse{\_}args()}, \var{options.filename} is |
| 338 | \code{"foo.txt"}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 339 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 340 | Some other option types supported by \module{optparse} are \code{int} and \code{float}. |
| 341 | Here's an option that expects an integer argument: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 342 | \begin{verbatim} |
| 343 | parser.add_option("-n", type="int", dest="num") |
| 344 | \end{verbatim} |
| 345 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 346 | Note that this option has no long option string, which is perfectly |
| 347 | acceptable. Also, there's no explicit action, since the default is |
| 348 | \code{store}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 349 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 350 | Let's parse another fake command-line. This time, we'll jam the option |
| 351 | argument right up against the option: since \code{"-n42"} (one argument) is |
| 352 | equivalent to \code{"-n 42"} (two arguments), the code |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 353 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 354 | (options, args) = parser.parse_args(["-n42"]) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 355 | print options.num |
| 356 | \end{verbatim} |
| 357 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 358 | will print \code{"42"}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 359 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 360 | If you don't specify a type, \module{optparse} assumes \code{string}. Combined with the |
| 361 | fact that the default action is \code{store}, that means our first example |
| 362 | can be a lot shorter: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 363 | \begin{verbatim} |
| 364 | parser.add_option("-f", "--file", dest="filename") |
| 365 | \end{verbatim} |
| 366 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 367 | If you don't supply a destination, \module{optparse} figures out a sensible default |
| 368 | from the option strings: if the first long option string is |
| 369 | \code{"-{}-foo-bar"}, then the default destination is \code{foo{\_}bar}. If there |
| 370 | are no long option strings, \module{optparse} looks at the first short option |
| 371 | string: the default destination for \code{"-f"} is \code{f}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 372 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 373 | \module{optparse} also includes built-in \code{long} and \code{complex} types. Adding |
| 374 | types is covered in section~\ref{optparse-extending}, Extending \module{optparse}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 375 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 376 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 377 | \subsubsection{Handling flag (boolean) options\label{optparse-handling-flag-(boolean)-options}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 378 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 379 | Flag options{---}set a variable to true or false when a particular option |
| 380 | is seen{---}are quite common. \module{optparse} supports them with two separate |
| 381 | actions, \code{store{\_}true} and \code{store{\_}false}. For example, you might have a |
| 382 | \var{verbose} flag that is turned on with \code{"-v"} and off with \code{"-q"}: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 383 | \begin{verbatim} |
| 384 | parser.add_option("-v", action="store_true", dest="verbose") |
| 385 | parser.add_option("-q", action="store_false", dest="verbose") |
| 386 | \end{verbatim} |
| 387 | |
| 388 | Here we have two different options with the same destination, which is |
| 389 | perfectly OK. (It just means you have to be a bit careful when setting |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 390 | default values{---}see section~\ref{optparse-default-values}, Default values, below.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 391 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 392 | When \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 Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 395 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 396 | |
| 397 | \subsubsection{Other actions\label{optparse-other-actions}} |
| 398 | |
| 399 | Some other actions supported by \module{optparse} are: |
| 400 | \begin{description} |
| 401 | \item[\code{store{\_}const}] |
| 402 | store a constant value |
| 403 | \item[\code{append}] |
| 404 | append this option's argument to a list |
| 405 | \item[\code{count}] |
| 406 | increment a counter by one |
| 407 | \item[\code{callback}] |
| 408 | call a specified function |
| 409 | \end{description} |
| 410 | |
| 411 | These are covered in the section~\ref{None}, Reference Guide and section~\ref{None}, Option Callbacks |
| 412 | documents. |
| 413 | |
| 414 | |
| 415 | \subsubsection{Default values\label{optparse-default-values}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 416 | |
| 417 | All of the above examples involve setting some variable (the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 418 | ``destination'') when certain command-line options are seen. What happens |
| 419 | if those options are never seen? Since we didn't supply any defaults, |
| 420 | they are all set to \code{None}. This is usually fine, but sometimes you |
| 421 | want more control. \module{optparse} lets you supply a default value for each |
| 422 | destination, which is assigned before the command line is parsed. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 423 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 424 | First, consider the verbose/quiet example. If we want \module{optparse} to set |
| 425 | \var{verbose} to \code{True} unless \code{"-q"} is seen, then we can do this: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 426 | \begin{verbatim} |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 427 | parser.add_option("-v", action="store_true", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 428 | parser.add_option("-q", action="store_false", dest="verbose") |
| 429 | \end{verbatim} |
| 430 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 431 | Since default values apply to the \emph{destination} rather than to any |
| 432 | particular option, and these two options happen to have the same |
| 433 | destination, this is exactly equivalent: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 434 | \begin{verbatim} |
| 435 | parser.add_option("-v", action="store_true", dest="verbose") |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 436 | parser.add_option("-q", action="store_false", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 437 | \end{verbatim} |
| 438 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 439 | Consider this: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 440 | \begin{verbatim} |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 441 | parser.add_option("-v", action="store_true", dest="verbose", default=False) |
| 442 | parser.add_option("-q", action="store_false", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 443 | \end{verbatim} |
| 444 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 445 | Again, the default value for \var{verbose} will be \code{True}: the last |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 446 | default value supplied for any particular destination is the one that |
| 447 | counts. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 448 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 449 | A clearer way to specify default values is the \method{set{\_}defaults()} |
| 450 | method of OptionParser, which you can call at any time before calling |
| 451 | \method{parse{\_}args()}: |
| 452 | \begin{verbatim} |
| 453 | parser.set_defaults(verbose=True) |
| 454 | parser.add_option(...) |
| 455 | (options, args) = parser.parse_args() |
| 456 | \end{verbatim} |
| 457 | |
| 458 | As before, the last value specified for a given option destination is |
| 459 | the one that counts. For clarity, try to use one method or the other of |
| 460 | setting default values, not both. |
| 461 | |
| 462 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 463 | \subsubsection{Generating help\label{optparse-generating-help}} |
| 464 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 465 | \module{optparse}'s ability to generate help and usage text automatically is useful |
| 466 | for creating user-friendly command-line interfaces. All you have to do |
| 467 | is supply a \member{help} value for each option, and optionally a short usage |
| 468 | message for your whole program. Here's an OptionParser populated with |
| 469 | user-friendly (documented) options: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 470 | \begin{verbatim} |
| 471 | usage = "usage: %prog [options] arg1 arg2" |
| 472 | parser = OptionParser(usage=usage) |
| 473 | parser.add_option("-v", "--verbose", |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 474 | action="store_true", dest="verbose", default=True, |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 475 | help="make lots of noise [default]") |
| 476 | parser.add_option("-q", "--quiet", |
| 477 | action="store_false", dest="verbose", |
| 478 | help="be vewwy quiet (I'm hunting wabbits)") |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 479 | parser.add_option("-f", "--filename", |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 480 | metavar="FILE", help="write output to FILE"), |
| 481 | parser.add_option("-m", "--mode", |
| 482 | default="intermediate", |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 483 | help="interaction mode: novice, intermediate, " |
| 484 | "or expert [default: %default]") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 485 | \end{verbatim} |
| 486 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 487 | If \module{optparse} encounters either \code{"-h"} or \code{"-{}-help"} on the command-line, |
| 488 | or if you just call \method{parser.print{\_}help()}, it prints the following to |
| 489 | standard output: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 490 | \begin{verbatim} |
| 491 | usage: <yourscript> [options] arg1 arg2 |
| 492 | |
| 493 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 494 | -h, --help show this help message and exit |
| 495 | -v, --verbose make lots of noise [default] |
| 496 | -q, --quiet be vewwy quiet (I'm hunting wabbits) |
| 497 | -f FILE, --filename=FILE |
| 498 | write output to FILE |
| 499 | -m MODE, --mode=MODE interaction mode: novice, intermediate, or |
| 500 | expert [default: intermediate] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 501 | \end{verbatim} |
| 502 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 503 | (If the help output is triggered by a help option, \module{optparse} exits after |
| 504 | printing the help text.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 505 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 506 | There's a lot going on here to help \module{optparse} generate the best possible |
| 507 | help message: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 508 | \begin{itemize} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 509 | \item {} |
| 510 | the script defines its own usage message: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 511 | \begin{verbatim} |
| 512 | usage = "usage: %prog [options] arg1 arg2" |
| 513 | \end{verbatim} |
| 514 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 515 | \module{optparse} expands \code{"{\%}prog"} in the usage string to the name of the current |
| 516 | program, i.e. \code{os.path.basename(sys.argv{[}0])}. The expanded string |
| 517 | is then printed before the detailed option help. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 518 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 519 | If you don't supply a usage string, \module{optparse} uses a bland but sensible |
| 520 | default: ``\code{usage: {\%}prog {[}options]"}, which is fine if your script |
| 521 | doesn't take any positional arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 522 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 523 | \item {} |
| 524 | every option defines a help string, and doesn't worry about line- |
| 525 | wrapping{---}\module{optparse} takes care of wrapping lines and making the |
| 526 | help output look good. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 527 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 528 | \item {} |
| 529 | options that take a value indicate this fact in their |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 530 | automatically-generated help message, e.g. for the ``mode'' option: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 531 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 532 | -m MODE, --mode=MODE |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 533 | \end{verbatim} |
| 534 | |
| 535 | Here, ``MODE'' is called the meta-variable: it stands for the argument |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 536 | that the user is expected to supply to \programopt{-m}/\longprogramopt{mode}. By default, |
| 537 | \module{optparse} converts the destination variable name to uppercase and uses |
| 538 | that for the meta-variable. Sometimes, that's not what you want{---}for example, the \longprogramopt{filename} option explicitly sets |
| 539 | \code{metavar="FILE"}, resulting in this automatically-generated option |
| 540 | description: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 541 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 542 | -f FILE, --filename=FILE |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 543 | \end{verbatim} |
| 544 | |
| 545 | This is important for more than just saving space, though: the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 546 | manually written help text uses the meta-variable ``FILE'' to clue the |
| 547 | user in that there's a connection between the semi-formal syntax ``-f |
| 548 | FILE'' and the informal semantic description ``write output to FILE''. |
| 549 | This is a simple but effective way to make your help text a lot |
| 550 | clearer and more useful for end users. |
| 551 | |
| 552 | \item {} |
| 553 | options that have a default value can include \code{{\%}default} in |
| 554 | the help string{---}\module{optparse} will replace it with \function{str()} of the |
| 555 | option's default value. If an option has no default value (or the |
| 556 | default value is \code{None}), \code{{\%}default} expands to \code{none}. |
| 557 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 558 | \end{itemize} |
| 559 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 560 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 561 | \subsubsection{Printing a version string\label{optparse-printing-a-version-string}} |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 562 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 563 | Similar to the brief usage string, \module{optparse} can also print a version string |
| 564 | for your program. You have to supply the string as the \code{version} |
| 565 | argument to OptionParser: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 566 | \begin{verbatim} |
| 567 | parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") |
| 568 | \end{verbatim} |
| 569 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 570 | Note that \code{"{\%}prog"} is expanded just like it is in \var{usage}. Apart |
| 571 | from that, \code{version} can contain anything you like. When you supply |
| 572 | it, \module{optparse} automatically adds a \code{"-{}-version"} option to your parser. |
| 573 | If it encounters this option on the command line, it expands your |
| 574 | \code{version} string (by replacing \code{"{\%}prog"}), prints it to stdout, and |
| 575 | exits. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 576 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 577 | For example, if your script is called \code{/usr/bin/foo}: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 578 | \begin{verbatim} |
| 579 | $ /usr/bin/foo --version |
| 580 | foo 1.0 |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 581 | \end{verbatim} |
| 582 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 583 | |
| 584 | \subsubsection{Error-handling\label{optparse-error-handling}} |
| 585 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 586 | There are two broad classes of errors that \module{optparse} has to worry about: |
| 587 | programmer errors and user errors. Programmer errors are usually |
| 588 | erroneous calls to \code{parse.add{\_}option()}, e.g. invalid option strings, |
| 589 | unknown option attributes, missing option attributes, etc. These are |
| 590 | dealt with in the usual way: raise an exception (either |
| 591 | \code{optparse.OptionError} or \code{TypeError}) and let the program crash. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 592 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 593 | Handling user errors is much more important, since they are guaranteed |
| 594 | to happen no matter how stable your code is. \module{optparse} can automatically |
| 595 | detect some user errors, such as bad option arguments (passing \code{"-n |
| 596 | 4x"} where \programopt{-n} takes an integer argument), missing arguments |
| 597 | (\code{"-n"} at the end of the command line, where \programopt{-n} takes an argument |
| 598 | of any type). Also, you can call \code{parser.error()} to signal an |
| 599 | application-defined error condition: |
| 600 | \begin{verbatim} |
| 601 | (options, args) = parser.parse_args() |
| 602 | [...] |
| 603 | if options.a and options.b: |
| 604 | parser.error("options -a and -b are mutually exclusive") |
| 605 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 606 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 607 | In either case, \module{optparse} handles the error the same way: it prints the |
| 608 | program's usage message and an error message to standard error and |
| 609 | exits with error status 2. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 610 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 611 | Consider the first example above, where the user passes \code{"4x"} to an |
| 612 | option that takes an integer: |
| 613 | \begin{verbatim} |
| 614 | $ /usr/bin/foo -n 4x |
| 615 | usage: foo [options] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 616 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 617 | foo: error: option -n: invalid integer value: '4x' |
| 618 | \end{verbatim} |
| 619 | |
| 620 | Or, where the user fails to pass a value at all: |
| 621 | \begin{verbatim} |
| 622 | $ /usr/bin/foo -n |
| 623 | usage: foo [options] |
| 624 | |
| 625 | foo: error: -n option requires an argument |
| 626 | \end{verbatim} |
| 627 | |
| 628 | \module{optparse}-generated error messages take care always to mention the option |
| 629 | involved in the error; be sure to do the same when calling |
| 630 | \code{parser.error()} from your application code. |
| 631 | |
| 632 | If \module{optparse}'s default error-handling behaviour does not suite your needs, |
| 633 | you'll need to subclass OptionParser and override \code{exit()} and/or |
| 634 | \method{error()}. |
| 635 | |
| 636 | |
| 637 | \subsubsection{Putting it all together\label{optparse-putting-it-all-together}} |
| 638 | |
| 639 | Here's what \module{optparse}-based scripts usually look like: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 640 | \begin{verbatim} |
| 641 | from optparse import OptionParser |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 642 | [...] |
| 643 | def main(): |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 644 | usage = "usage: %prog [options] arg" |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 645 | parser = OptionParser(usage) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 646 | parser.add_option("-f", "--file", dest="filename", |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 647 | help="read data from FILENAME") |
| 648 | parser.add_option("-v", "--verbose", |
| 649 | action="store_true", dest="verbose") |
| 650 | parser.add_option("-q", "--quiet", |
| 651 | action="store_false", dest="verbose") |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 652 | [...] |
| 653 | (options, args) = parser.parse_args() |
| 654 | if len(args) != 1: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 655 | parser.error("incorrect number of arguments") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 656 | if options.verbose: |
Johannes Gijsbers | c9c37ca | 2004-09-11 15:47:30 +0000 | [diff] [blame] | 657 | print "reading %s..." % options.filename |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 658 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 659 | |
| 660 | if __name__ == "__main__": |
| 661 | main() |
| 662 | \end{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 663 | % $Id$ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 664 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 665 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 666 | \subsection{Reference Guide\label{optparse-reference-guide}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 667 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 668 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 669 | \subsubsection{Populating the parser\label{optparse-populating-the-parser}} |
| 670 | |
| 671 | There are several ways to populate the parser with options. The |
| 672 | preferred way is by using \code{OptionParser.add{\_}option()}, as shown in |
| 673 | section~\ref{None}, the tutorial section. \method{add{\_}option()} can be called in one of two |
| 674 | ways: |
| 675 | \begin{itemize} |
| 676 | \item {} |
| 677 | pass it an Option instance (as returned by \function{make{\_}option()}) |
| 678 | |
| 679 | \item {} |
| 680 | pass it any combination of positional and keyword arguments that are |
| 681 | acceptable to \function{make{\_}option()} (i.e., to the Option constructor), |
| 682 | and it will create the Option instance for you |
| 683 | |
| 684 | \end{itemize} |
| 685 | |
| 686 | The other alternative is to pass a list of pre-constructed Option |
| 687 | instances to the OptionParser constructor, as in: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 688 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 689 | option_list = [ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 690 | make_option("-f", "--filename", |
| 691 | action="store", type="string", dest="filename"), |
| 692 | make_option("-q", "--quiet", |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 693 | action="store_false", dest="verbose"), |
| 694 | ] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 695 | parser = OptionParser(option_list=option_list) |
| 696 | \end{verbatim} |
| 697 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 698 | (\function{make{\_}option()} is a factory function for creating Option instances; |
| 699 | currently it is an alias for the Option constructor. A future version |
| 700 | of \module{optparse} may split Option into several classes, and \function{make{\_}option()} |
| 701 | will pick the right class to instantiate. Do not instantiate Option |
| 702 | directly.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 703 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 704 | |
| 705 | \subsubsection{Defining options\label{optparse-defining-options}} |
| 706 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 707 | Each Option instance represents a set of synonymous command-line option |
| 708 | strings, e.g. programopt{\{}f{\}} and longprogramopt{\{}--file{\}}. You can |
| 709 | specify any number of short or long option strings, but you must specify |
| 710 | at least one overall option string. |
| 711 | |
| 712 | The canonical way to create an Option instance is by calling |
| 713 | \function{make{\_}option()}, so that is what will be shown here. However, the |
| 714 | most common and convenient way is to use \code{parser.add{\_}option()}. Note |
| 715 | that \function{make{\_}option()} and \code{parser.add{\_}option()} have identical call |
| 716 | signatures: |
| 717 | \begin{verbatim} |
| 718 | make_option(opt_str, ..., attr=value, ...) |
| 719 | parser.add_option(opt_str, ..., attr=value, ...) |
| 720 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 721 | |
| 722 | To define an option with only a short option string: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 723 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 724 | make_option("-f", attr=value, ...) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 725 | \end{verbatim} |
| 726 | |
| 727 | And to define an option with only a long option string: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 728 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 729 | make_option("--foo", attr=value, ...) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 730 | \end{verbatim} |
| 731 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 732 | The \code{attr=value} keyword arguments define option attributes, |
| 733 | i.e. attributes of the Option object. The most important option |
| 734 | attribute is \member{action}, and it largely determines what other attributes |
| 735 | are relevant or required. If you pass irrelevant option attributes, or |
| 736 | fail to pass required ones, \module{optparse} raises an OptionError exception |
| 737 | explaining your mistake. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 738 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 739 | An options's \emph{action} determines what \module{optparse} does when it encounters |
| 740 | this option on the command-line. The actions hard-coded into \module{optparse} are: |
| 741 | \begin{description} |
| 742 | \item[\code{store}] |
| 743 | store this option's argument {[}default] |
| 744 | \item[\code{store{\_}const}] |
| 745 | store a constant value |
| 746 | \item[\code{store{\_}true}] |
| 747 | store a true value |
| 748 | \item[\code{store{\_}false}] |
| 749 | store a false value |
| 750 | \item[\code{append}] |
| 751 | append this option's argument to a list |
| 752 | \item[\code{count}] |
| 753 | increment a counter by one |
| 754 | \item[\code{callback}] |
| 755 | call a specified function |
| 756 | \item[\member{help}] |
| 757 | print a usage message including all options and the |
| 758 | documentation for them |
| 759 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 760 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 761 | (If you don't supply an action, the default is \code{store}. For this |
| 762 | action, you may also supply \member{type} and \member{dest} option attributes; see |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 763 | below.) |
| 764 | |
| 765 | As you can see, most actions involve storing or updating a value |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 766 | somewhere. \module{optparse} always creates an instance of \code{optparse.Values} |
| 767 | specifically for this purpose; we refer to this instance as \var{options}. |
| 768 | Option arguments (and various other values) are stored as attributes of |
| 769 | this object, according to the \member{dest} (destination) option attribute. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 770 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 771 | For example, when you call |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 772 | \begin{verbatim} |
| 773 | parser.parse_args() |
| 774 | \end{verbatim} |
| 775 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 776 | one of the first things \module{optparse} does is create the \var{options} object: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 777 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 778 | options = Values() |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 779 | \end{verbatim} |
| 780 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 781 | If one of the options in this parser is defined with |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 782 | \begin{verbatim} |
| 783 | make_option("-f", "--file", action="store", type="string", dest="filename") |
| 784 | \end{verbatim} |
| 785 | |
| 786 | and the command-line being parsed includes any of the following: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 787 | \begin{verbatim} |
| 788 | -ffoo |
| 789 | -f foo |
| 790 | --file=foo |
| 791 | --file foo |
| 792 | \end{verbatim} |
| 793 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 794 | then \module{optparse}, on seeing the \programopt{-f} or \longprogramopt{file} option, will do the |
| 795 | equivalent of |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 796 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 797 | options.filename = "foo" |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 798 | \end{verbatim} |
| 799 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 800 | The \member{type} and \member{dest} option attributes are almost as important as |
| 801 | \member{action}, but \member{action} is the only one that makes sense for \emph{all} |
| 802 | options. |
| 803 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 804 | |
| 805 | \subsubsection{Option actions\label{optparse-option-actions}} |
| 806 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 807 | The various option actions all have slightly different requirements and |
| 808 | effects. Most actions have several relevant option attributes which you |
| 809 | may specify to guide \module{optparse}'s behaviour; a few have required attributes, |
| 810 | which you must specify for any option using that action. |
| 811 | \begin{itemize} |
| 812 | \item {} |
| 813 | \code{store} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 814 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 815 | The option must be followed by an argument, which is |
| 816 | converted to a value according to \member{type} and stored in |
| 817 | \member{dest}. If \code{nargs} {\textgreater} 1, multiple arguments will be consumed |
| 818 | from the command line; all will be converted according to |
| 819 | \member{type} and stored to \member{dest} as a tuple. See the ``Option |
| 820 | types'' section below. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 821 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 822 | If \code{choices} is supplied (a list or tuple of strings), the type |
| 823 | defaults to \code{choice}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 824 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 825 | If \member{type} is not supplied, it defaults to \code{string}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 826 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 827 | If \member{dest} is not supplied, \module{optparse} derives a destination from the |
| 828 | first long option string (e.g., \code{"-{}-foo-bar"} implies \code{foo{\_}bar}). |
| 829 | If there are no long option strings, \module{optparse} derives a destination from |
| 830 | the first short option string (e.g., \code{"-f"} implies \code{f}). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 831 | |
| 832 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 833 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 834 | parser.add_option("-f") |
| 835 | parser.add_option("-p", type="float", nargs=3, dest="point") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 836 | \end{verbatim} |
| 837 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 838 | As it parses the command line |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 839 | \begin{verbatim} |
| 840 | -f foo.txt -p 1 -3.5 4 -fbar.txt |
| 841 | \end{verbatim} |
| 842 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 843 | \module{optparse} will set |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 844 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 845 | options.f = "foo.txt" |
| 846 | options.point = (1.0, -3.5, 4.0) |
| 847 | options.f = "bar.txt" |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 848 | \end{verbatim} |
| 849 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 850 | \item {} |
| 851 | \code{store{\_}const} {[}required: \code{const}; relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 852 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 853 | The value \code{const} is stored in \member{dest}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 854 | |
| 855 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 856 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 857 | parser.add_option("-q", "--quiet", |
| 858 | action="store_const", const=0, dest="verbose") |
| 859 | parser.add_option("-v", "--verbose", |
| 860 | action="store_const", const=1, dest="verbose") |
| 861 | parser.add_option("--noisy", |
| 862 | action="store_const", const=2, dest="verbose") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 863 | \end{verbatim} |
| 864 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 865 | If \code{"-{}-noisy"} is seen, \module{optparse} will set |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 866 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 867 | options.verbose = 2 |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 868 | \end{verbatim} |
| 869 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 870 | \item {} |
| 871 | \code{store{\_}true} {[}relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 872 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 873 | A special case of \code{store{\_}const} that stores a true value |
| 874 | to \member{dest}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 875 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 876 | \item {} |
| 877 | \code{store{\_}false} {[}relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 878 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 879 | Like \code{store{\_}true}, but stores a false value. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 880 | |
| 881 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 882 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 883 | parser.add_option("--clobber", action="store_true", dest="clobber") |
| 884 | parser.add_option("--no-clobber", action="store_false", dest="clobber") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 885 | \end{verbatim} |
| 886 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 887 | \item {} |
| 888 | \code{append} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 889 | |
| 890 | The option must be followed by an argument, which is appended to the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 891 | list in \member{dest}. If no default value for \member{dest} is supplied, an |
| 892 | empty list is automatically created when \module{optparse} first encounters this |
| 893 | option on the command-line. If \code{nargs} {\textgreater} 1, multiple arguments are |
| 894 | consumed, and a tuple of length \code{nargs} is appended to \member{dest}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 895 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 896 | The defaults for \member{type} and \member{dest} are the same as for the |
| 897 | \code{store} action. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 898 | |
| 899 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 900 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 901 | parser.add_option("-t", "--tracks", action="append", type="int") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 902 | \end{verbatim} |
| 903 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 904 | If \code{"-t3"} is seen on the command-line, \module{optparse} does the equivalent of: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 905 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 906 | options.tracks = [] |
| 907 | options.tracks.append(int("3")) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 908 | \end{verbatim} |
| 909 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 910 | If, a little later on, \code{"-{}-tracks=4"} is seen, it does: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 911 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 912 | options.tracks.append(int("4")) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 913 | \end{verbatim} |
| 914 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 915 | \item {} |
| 916 | \code{count} {[}relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 917 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 918 | Increment the integer stored at \member{dest}. If no default value is |
| 919 | supplied, \member{dest} is set to zero before being incremented the first |
| 920 | time. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 921 | |
| 922 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 923 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 924 | parser.add_option("-v", action="count", dest="verbosity") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 925 | \end{verbatim} |
| 926 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 927 | The first time \code{"-v"} is seen on the command line, \module{optparse} does the |
| 928 | equivalent of: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 929 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 930 | options.verbosity = 0 |
| 931 | options.verbosity += 1 |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 932 | \end{verbatim} |
| 933 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 934 | Every subsequent occurrence of \code{"-v"} results in |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 935 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 936 | options.verbosity += 1 |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 937 | \end{verbatim} |
| 938 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 939 | \item {} |
| 940 | \code{callback} {[}required: \code{callback}; |
| 941 | relevant: \member{type}, \code{nargs}, \code{callback{\_}args}, \code{callback{\_}kwargs}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 942 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 943 | Call the function specified by \code{callback}. The signature of |
| 944 | this function should be |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 945 | \begin{verbatim} |
| 946 | func(option : Option, |
| 947 | opt : string, |
| 948 | value : any, |
| 949 | parser : OptionParser, |
| 950 | *args, **kwargs) |
| 951 | \end{verbatim} |
| 952 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 953 | See section~\ref{None}, Option Callbacks for more detail. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 954 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 955 | \item {} |
| 956 | \member{help} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 957 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 958 | Prints a complete help message for all the options in the |
| 959 | current option parser. The help message is constructed from |
| 960 | the \var{usage} string passed to OptionParser's constructor and |
| 961 | the \member{help} string passed to every option. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 962 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 963 | If no \member{help} string is supplied for an option, it will still be |
| 964 | listed in the help message. To omit an option entirely, use |
| 965 | the special value \code{optparse.SUPPRESS{\_}HELP}. |
| 966 | |
| 967 | \module{optparse} automatically adds a \member{help} option to all OptionParsers, so |
| 968 | you do not normally need to create one. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 969 | |
| 970 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 971 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 972 | from optparse import OptionParser, SUPPRESS_HELP |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 973 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 974 | parser = OptionParser() |
| 975 | parser.add_option("-h", "--help", action="help"), |
| 976 | parser.add_option("-v", action="store_true", dest="verbose", |
| 977 | help="Be moderately verbose") |
| 978 | parser.add_option("--file", dest="filename", |
| 979 | help="Input file to read data from"), |
| 980 | parser.add_option("--secret", help=SUPPRESS_HELP) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 981 | \end{verbatim} |
| 982 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 983 | If \module{optparse} sees either \code{"-h"} or \code{"-{}-help"} on the command line, it |
| 984 | will print something like the following help message to stdout |
| 985 | (assuming \code{sys.argv{[}0]} is \code{"foo.py"}): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 986 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 987 | usage: foo.py [options] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 988 | |
| 989 | options: |
| 990 | -h, --help Show this help message and exit |
| 991 | -v Be moderately verbose |
| 992 | --file=FILENAME Input file to read data from |
| 993 | \end{verbatim} |
| 994 | |
| 995 | After printing the help message, \module{optparse} terminates your process |
| 996 | with \code{sys.exit(0)}. |
| 997 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 998 | \item {} |
| 999 | \code{version} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1000 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1001 | Prints the version number supplied to the OptionParser to stdout and |
| 1002 | exits. The version number is actually formatted and printed by the |
| 1003 | \code{print{\_}version()} method of OptionParser. Generally only relevant |
| 1004 | if the \code{version} argument is supplied to the OptionParser |
| 1005 | constructor. As with \member{help} options, you will rarely create |
| 1006 | \code{version} options, since \module{optparse} automatically adds them when needed. |
| 1007 | |
| 1008 | \end{itemize} |
| 1009 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1010 | |
| 1011 | \subsubsection{Option types\label{optparse-option-types}} |
| 1012 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1013 | \module{optparse} has six built-in option types: \code{string}, \code{int}, \code{long}, |
| 1014 | \code{choice}, \code{float} and \code{complex}. If you need to add new option |
| 1015 | types, see section~\ref{optparse-extending}, Extending \module{optparse}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1016 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1017 | Arguments to string options are not checked or converted in any way: the |
| 1018 | text on the command line is stored in the destination (or passed to the |
| 1019 | callback) as-is. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1020 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1021 | Integer arguments are passed to \code{int()} to convert them to Python |
| 1022 | integers. If \code{int()} fails, so will \module{optparse}, although with a more |
| 1023 | useful error message. (Internally, \module{optparse} raises OptionValueError; |
| 1024 | OptionParser catches this exception higher up and terminates your |
| 1025 | program with a useful error message.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1026 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1027 | Likewise, \code{float} arguments are passed to \code{float()} for conversion, |
| 1028 | \code{long} arguments to \code{long()}, and \code{complex} arguments to |
| 1029 | \code{complex()}. Apart from that, they are handled identically to integer |
| 1030 | arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1031 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1032 | \code{choice} options are a subtype of \code{string} options. The \code{choices} |
| 1033 | option attribute (a sequence of strings) defines the set of allowed |
| 1034 | option arguments. \code{optparse.option.check{\_}choice()} compares |
| 1035 | user-supplied option arguments against this master list and raises |
| 1036 | OptionValueError if an invalid string is given. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1037 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1038 | |
| 1039 | \subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating-your-option-parser}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1040 | |
| 1041 | Sometimes, it's useful to poke around your option parser and see what's |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1042 | there. OptionParser provides a couple of methods to help you out: |
| 1043 | \begin{description} |
| 1044 | \item[\code{has{\_}option(opt{\_}str)}] |
| 1045 | Return true if the OptionParser has an option with |
| 1046 | option string \code{opt{\_}str} (e.g., \code{"-q"} or \code{"-{}-verbose"}). |
| 1047 | \item[\code{get{\_}option(opt{\_}str)}] |
| 1048 | Returns the Option instance with the option string \code{opt{\_}str}, or |
| 1049 | \code{None} if no options have that option string. |
| 1050 | \item[\code{remove{\_}option(opt{\_}str)}] |
| 1051 | If the OptionParser has an option corresponding to \code{opt{\_}str}, |
| 1052 | that option is removed. If that option provided any other |
| 1053 | option strings, all of those option strings become invalid. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1054 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1055 | If \code{opt{\_}str} does not occur in any option belonging to this |
| 1056 | OptionParser, raises ValueError. |
| 1057 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1058 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1059 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1060 | \subsubsection{Conflicts between options\label{optparse-conflicts-between-options}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1061 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1062 | If you're not careful, it's easy to define options with conflicting |
| 1063 | option strings: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1064 | \begin{verbatim} |
| 1065 | parser.add_option("-n", "--dry-run", ...) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1066 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1067 | parser.add_option("-n", "--noisy", ...) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1068 | \end{verbatim} |
| 1069 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1070 | (This is particularly true if you've defined your own OptionParser |
| 1071 | subclass with some standard options.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1072 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1073 | Every time you add an option, \module{optparse} checks for conflicts with existing |
| 1074 | options. If it finds any, it invokes the current conflict-handling |
| 1075 | mechanism. You can set the conflict-handling mechanism either in the |
| 1076 | constructor: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1077 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1078 | parser = OptionParser(..., conflict_handler="...") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1079 | \end{verbatim} |
| 1080 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1081 | or with a separate call: |
| 1082 | \begin{verbatim} |
| 1083 | parser.set_conflict_handler("...") |
| 1084 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1085 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1086 | The available conflict-handling mechanisms are: |
| 1087 | \begin{quote} |
| 1088 | \begin{description} |
| 1089 | \item[\code{error} (default)] |
| 1090 | assume option conflicts are a programming error and raise |
| 1091 | OptionConflictError |
| 1092 | \item[\code{resolve}] |
| 1093 | resolve option conflicts intelligently (see below) |
| 1094 | \end{description} |
| 1095 | \end{quote} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1096 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1097 | As an example, let's define an OptionParser that resolves conflicts |
| 1098 | intelligently and add conflicting options to it: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1099 | \begin{verbatim} |
| 1100 | parser = OptionParser(conflict_handler="resolve") |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1101 | parser.add_option("-n", "--dry-run", ..., help="do no harm") |
| 1102 | parser.add_option("-n", "--noisy", ..., help="be noisy") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1103 | \end{verbatim} |
| 1104 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1105 | At this point, \module{optparse} detects that a previously-added option is already |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1106 | using the \code{"-n"} option string. Since \code{conflict{\_}handler} is |
| 1107 | \code{"resolve"}, it resolves the situation by removing \code{"-n"} from the |
| 1108 | earlier option's list of option strings. Now \code{"-{}-dry-run"} is the |
| 1109 | only way for the user to activate that option. If the user asks for |
| 1110 | help, the help message will reflect that: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1111 | \begin{verbatim} |
| 1112 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1113 | --dry-run do no harm |
| 1114 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1115 | -n, --noisy be noisy |
| 1116 | \end{verbatim} |
| 1117 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1118 | It's possible to whittle away the option strings for a previously-added |
| 1119 | option until there are none left, and the user has no way of invoking |
| 1120 | that option from the command-line. In that case, \module{optparse} removes that |
| 1121 | option completely, so it doesn't show up in help text or anywhere else. |
| 1122 | Carrying on with our existing OptionParser: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1123 | \begin{verbatim} |
| 1124 | parser.add_option("--dry-run", ..., help="new dry-run option") |
| 1125 | \end{verbatim} |
| 1126 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1127 | At this point, the original \programopt{-n/-{}-dry-run} option is no longer |
| 1128 | accessible, so \module{optparse} removes it, leaving this help text: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1129 | \begin{verbatim} |
| 1130 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1131 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1132 | -n, --noisy be noisy |
| 1133 | --dry-run new dry-run option |
| 1134 | \end{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1135 | % $Id$ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1136 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1137 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1138 | \subsection{Option Callbacks\label{optparse-option-callbacks}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1139 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1140 | When \module{optparse}'s built-in actions and types aren't quite enough for your |
| 1141 | needs, you have two choices: extend \module{optparse} or define a callback option. |
| 1142 | Extending \module{optparse} is more general, but overkill for a lot of simple |
| 1143 | cases. Quite often a simple callback is all you need. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1144 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1145 | There are two steps to defining a callback option: |
| 1146 | \begin{itemize} |
| 1147 | \item {} |
| 1148 | define the option itself using the \code{callback} action |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1149 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1150 | \item {} |
| 1151 | write the callback; this is a function (or method) that |
| 1152 | takes at least four arguments, as described below |
| 1153 | |
| 1154 | \end{itemize} |
| 1155 | |
| 1156 | |
| 1157 | \subsubsection{Defining a callback option\label{optparse-defining-a-callback-option}} |
| 1158 | |
| 1159 | As always, the easiest way to define a callback option is by using the |
| 1160 | \code{parser.add{\_}option()} method. Apart from \member{action}, the only option |
| 1161 | attribute you must specify is \code{callback}, the function to call: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1162 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1163 | parser.add_option("-c", action="callback", callback=my_callback) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1164 | \end{verbatim} |
| 1165 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1166 | \code{callback} is a function (or other callable object), so you must have |
| 1167 | already defined \code{my{\_}callback()} when you create this callback option. |
| 1168 | In this simple case, \module{optparse} doesn't even know if \programopt{-c} takes any |
| 1169 | arguments, which usually means that the option takes no arguments{---}the |
| 1170 | mere presence of \programopt{-c} on the command-line is all it needs to know. In |
| 1171 | some circumstances, though, you might want your callback to consume an |
| 1172 | arbitrary number of command-line arguments. This is where writing |
| 1173 | callbacks gets tricky; it's covered later in this section. |
| 1174 | |
| 1175 | \module{optparse} always passes four particular arguments to your callback, and it |
| 1176 | will only pass additional arguments if you specify them via |
| 1177 | \code{callback{\_}args} and \code{callback{\_}kwargs}. Thus, the minimal callback |
| 1178 | function signature is: |
| 1179 | \begin{verbatim} |
| 1180 | def my_callback(option, opt, value, parser): |
| 1181 | \end{verbatim} |
| 1182 | |
| 1183 | The four arguments to a callback are described below. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1184 | |
| 1185 | There are several other option attributes that you can supply when you |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1186 | define a callback option: |
| 1187 | \begin{description} |
| 1188 | \item[\member{type}] |
| 1189 | has its usual meaning: as with the \code{store} or \code{append} actions, |
| 1190 | it instructs \module{optparse} to consume one argument and convert it to |
| 1191 | \member{type}. Rather than storing the converted value(s) anywhere, |
| 1192 | though, \module{optparse} passes it to your callback function. |
| 1193 | \item[\code{nargs}] |
| 1194 | also has its usual meaning: if it is supplied and {\textgreater} 1, \module{optparse} will |
| 1195 | consume \code{nargs} arguments, each of which must be convertible to |
| 1196 | \member{type}. It then passes a tuple of converted values to your |
| 1197 | callback. |
| 1198 | \item[\code{callback{\_}args}] |
| 1199 | a tuple of extra positional arguments to pass to the callback |
| 1200 | \item[\code{callback{\_}kwargs}] |
| 1201 | a dictionary of extra keyword arguments to pass to the callback |
| 1202 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1203 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1204 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1205 | \subsubsection{How callbacks are called\label{optparse-how-callbacks-are-called}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1206 | |
| 1207 | All callbacks are called as follows: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1208 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1209 | func(option, opt_str, value, parser, *args, **kwargs) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1210 | \end{verbatim} |
| 1211 | |
| 1212 | where |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1213 | \begin{description} |
| 1214 | \item[\code{option}] |
| 1215 | is the Option instance that's calling the callback |
| 1216 | \item[\code{opt{\_}str}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1217 | is the option string seen on the command-line that's triggering the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1218 | callback. (If an abbreviated long option was used, \code{opt{\_}str} will |
| 1219 | be the full, canonical option string{---}e.g. if the user puts |
| 1220 | \code{"-{}-foo"} on the command-line as an abbreviation for |
| 1221 | \code{"-{}-foobar"}, then \code{opt{\_}str} will be \code{"-{}-foobar"}.) |
| 1222 | \item[\code{value}] |
| 1223 | is the argument to this option seen on the command-line. \module{optparse} will |
| 1224 | only expect an argument if \member{type} is set; the type of \code{value} |
| 1225 | will be the type implied by the option's type. If \member{type} for this |
| 1226 | option is \code{None} (no argument expected), then \code{value} will be |
| 1227 | \code{None}. If \code{nargs} {\textgreater} 1, \code{value} will be a tuple of values of |
| 1228 | the appropriate type. |
| 1229 | \item[\code{parser}] |
| 1230 | is the OptionParser instance driving the whole thing, mainly |
| 1231 | useful because you can access some other interesting data through |
| 1232 | its instance attributes: |
| 1233 | \begin{description} |
| 1234 | \item[\code{parser.largs}] |
| 1235 | the current list of leftover arguments, ie. arguments that have |
| 1236 | been consumed but are neither options nor option arguments. |
| 1237 | Feel free to modify \code{parser.largs}, e.g. by adding more |
| 1238 | arguments to it. (This list will become \var{args}, the second |
| 1239 | return value of \method{parse{\_}args()}.) |
| 1240 | \item[\code{parser.rargs}] |
| 1241 | the current list of remaining arguments, ie. with \code{opt{\_}str} and |
| 1242 | \code{value} (if applicable) removed, and only the arguments |
| 1243 | following them still there. Feel free to modify |
| 1244 | \code{parser.rargs}, e.g. by consuming more arguments. |
| 1245 | \item[\code{parser.values}] |
| 1246 | the object where option values are by default stored (an |
| 1247 | instance of optparse.OptionValues). This lets callbacks use the |
| 1248 | same mechanism as the rest of \module{optparse} for storing option values; |
| 1249 | you don't need to mess around with globals or closures. You can |
| 1250 | also access or modify the value(s) of any options already |
| 1251 | encountered on the command-line. |
| 1252 | \end{description} |
| 1253 | \item[\var{args}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1254 | is a tuple of arbitrary positional arguments supplied via the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1255 | \code{callback{\_}args} option attribute. |
| 1256 | \item[\code{kwargs}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1257 | is a dictionary of arbitrary keyword arguments supplied via |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1258 | \code{callback{\_}kwargs}. |
| 1259 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1260 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1261 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1262 | \subsubsection{Error handling\label{optparse-error-handling}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1263 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1264 | The callback function should raise OptionValueError if there are any |
| 1265 | problems with the option or its argument(s). \module{optparse} catches this and |
| 1266 | terminates the program, printing the error message you supply to |
| 1267 | stderr. Your message should be clear, concise, accurate, and mention |
| 1268 | the option at fault. Otherwise, the user will have a hard time |
| 1269 | figuring out what he did wrong. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1270 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1271 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1272 | \subsubsection{Callback example 1: trivial callback\label{optparse-callback-example-1:-trivial-callback}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1273 | |
| 1274 | Here's an example of a callback option that takes no arguments, and |
| 1275 | simply records that the option was seen: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1276 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1277 | def record_foo_seen(option, opt_str, value, parser): |
| 1278 | parser.saw_foo = True |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1279 | |
| 1280 | parser.add_option("--foo", action="callback", callback=record_foo_seen) |
| 1281 | \end{verbatim} |
| 1282 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1283 | Of course, you could do that with the \code{store{\_}true} action. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1284 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1285 | |
| 1286 | \subsubsection{Callback example 2: check option order\label{optparse-callback-example-2:-check-option-order}} |
| 1287 | |
| 1288 | Here's a slightly more interesting example: record the fact that |
| 1289 | \code{"-a"} is seen, but blow up if it comes after \code{"-b"} in the |
| 1290 | command-line. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1291 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1292 | def check_order(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1293 | if parser.values.b: |
| 1294 | raise OptionValueError("can't use -a after -b") |
| 1295 | parser.values.a = 1 |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1296 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1297 | parser.add_option("-a", action="callback", callback=check_order) |
| 1298 | parser.add_option("-b", action="store_true", dest="b") |
| 1299 | \end{verbatim} |
| 1300 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1301 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1302 | \subsubsection{Callback example 3: check option order (generalized)\label{optparse-callback-example-3:-check-option-order-(generalized)}} |
| 1303 | |
| 1304 | If you want to re-use this callback for several similar options (set a |
| 1305 | flag, but blow up if \code{"-b"} has already been seen), it needs a bit of |
| 1306 | work: the error message and the flag that it sets must be |
| 1307 | generalized. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1308 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1309 | def check_order(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1310 | if parser.values.b: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1311 | raise OptionValueError("can't use %s after -b" % opt_str) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1312 | setattr(parser.values, option.dest, 1) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1313 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1314 | parser.add_option("-a", action="callback", callback=check_order, dest='a') |
| 1315 | parser.add_option("-b", action="store_true", dest="b") |
| 1316 | parser.add_option("-c", action="callback", callback=check_order, dest='c') |
| 1317 | \end{verbatim} |
| 1318 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1319 | |
| 1320 | \subsubsection{Callback example 4: check arbitrary condition\label{optparse-callback-example-4:-check-arbitrary-condition}} |
| 1321 | |
| 1322 | Of course, you could put any condition in there{---}you're not limited |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1323 | to checking the values of already-defined options. For example, if |
| 1324 | you have options that should not be called when the moon is full, all |
| 1325 | you have to do is this: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1326 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1327 | def check_moon(option, opt_str, value, parser): |
| 1328 | if is_moon_full(): |
| 1329 | raise OptionValueError("%s option invalid when moon is full" |
| 1330 | % opt_str) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1331 | setattr(parser.values, option.dest, 1) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1332 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1333 | parser.add_option("--foo", |
| 1334 | action="callback", callback=check_moon, dest="foo") |
| 1335 | \end{verbatim} |
| 1336 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1337 | (The definition of \code{is{\_}moon{\_}full()} is left as an exercise for the |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1338 | reader.) |
| 1339 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1340 | |
| 1341 | \subsubsection{Callback example 5: fixed arguments\label{optparse-callback-example-5:-fixed-arguments}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1342 | |
| 1343 | Things get slightly more interesting when you define callback options |
| 1344 | that take a fixed number of arguments. Specifying that a callback |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1345 | option takes arguments is similar to defining a \code{store} or \code{append} |
| 1346 | option: if you define \member{type}, then the option takes one argument that |
| 1347 | must be convertible to that type; if you further define \code{nargs}, then |
| 1348 | the option takes \code{nargs} arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1349 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1350 | Here's an example that just emulates the standard \code{store} action: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1351 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1352 | def store_value(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1353 | setattr(parser.values, option.dest, value) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1354 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1355 | parser.add_option("--foo", |
| 1356 | action="callback", callback=store_value, |
| 1357 | type="int", nargs=3, dest="foo") |
| 1358 | \end{verbatim} |
| 1359 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1360 | Note that \module{optparse} takes care of consuming 3 arguments and converting them |
| 1361 | to integers for you; all you have to do is store them. (Or whatever; |
| 1362 | obviously you don't need a callback for this example.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1363 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1364 | |
| 1365 | \subsubsection{Callback example 6: variable arguments\label{optparse-callback-example-6:-variable-arguments}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1366 | |
| 1367 | Things get hairy when you want an option to take a variable number of |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1368 | arguments. For this case, you must write a callback, as \module{optparse} doesn't |
| 1369 | provide any built-in capabilities for it. And you have to deal with |
| 1370 | certain intricacies of conventional \UNIX{} command-line parsing that \module{optparse} |
| 1371 | normally handles for you. In particular, callbacks should implement |
| 1372 | the conventional rules for bare \code{"-{}-"} and \code{"-"} arguments: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1373 | \begin{itemize} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1374 | \item {} |
| 1375 | either \code{"-{}-"} or \code{"-"} can be option arguments |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1376 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1377 | \item {} |
| 1378 | bare \code{"-{}-"} (if not the argument to some option): halt command-line |
| 1379 | processing and discard the \code{"-{}-"} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1380 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1381 | \item {} |
| 1382 | bare \code{"-"} (if not the argument to some option): halt command-line |
| 1383 | processing but keep the \code{"-"} (append it to \code{parser.largs}) |
| 1384 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1385 | \end{itemize} |
| 1386 | |
| 1387 | If you want an option that takes a variable number of arguments, there |
| 1388 | are several subtle, tricky issues to worry about. The exact |
| 1389 | implementation you choose will be based on which trade-offs you're |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1390 | willing to make for your application (which is why \module{optparse} doesn't support |
| 1391 | this sort of thing directly). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1392 | |
| 1393 | Nevertheless, here's a stab at a callback for an option with variable |
| 1394 | arguments: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1395 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1396 | def vararg_callback(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1397 | assert value is None |
| 1398 | done = 0 |
| 1399 | value = [] |
| 1400 | rargs = parser.rargs |
| 1401 | while rargs: |
| 1402 | arg = rargs[0] |
| 1403 | |
| 1404 | # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f", |
| 1405 | # etc. Note that this also stops on "-3" or "-3.0", so if |
| 1406 | # your option takes numeric values, you will need to handle |
| 1407 | # this. |
| 1408 | if ((arg[:2] == "--" and len(arg) > 2) or |
| 1409 | (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): |
| 1410 | break |
| 1411 | else: |
| 1412 | value.append(arg) |
| 1413 | del rargs[0] |
| 1414 | |
| 1415 | setattr(parser.values, option.dest, value) |
| 1416 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1417 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1418 | parser.add_option("-c", "--callback", |
| 1419 | action="callback", callback=varargs) |
| 1420 | \end{verbatim} |
| 1421 | |
| 1422 | The main weakness with this particular implementation is that negative |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1423 | numbers in the arguments following \code{"-c"} will be interpreted as |
| 1424 | further options (probably causing an error), rather than as arguments to |
| 1425 | \code{"-c"}. Fixing this is left as an exercise for the reader. |
| 1426 | % $Id$ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1427 | |