Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 1 | % THIS FILE IS AUTO-GENERATED! DO NOT EDIT! |
| 2 | % (Your changes will be lost the next time it is generated.) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 3 | \section{\module{optparse} --- More powerful command line option parser} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 4 | \declaremodule{standard}{optparse} |
| 5 | \moduleauthor{Greg Ward}{gward@python.net} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 6 | \modulesynopsis{More convenient, flexible, and powerful command-line parsing library.} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 7 | \versionadded{2.3} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 8 | \sectionauthor{Greg Ward}{gward@python.net} |
| 9 | % An intro blurb used only when generating LaTeX docs for the Python |
| 10 | % manual (based on README.txt). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 11 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 12 | \code{optparse} is a more convenient, flexible, and powerful library for |
| 13 | parsing command-line options than \code{getopt}. \code{optparse} uses a more |
| 14 | declarative style of command-line parsing: you create an instance of |
| 15 | \class{OptionParser}, populate it with options, and parse the command line. |
| 16 | \code{optparse} allows users to specify options in the conventional GNU/POSIX |
| 17 | syntax, and additionally generates usage and help messages for you. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 18 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 19 | Here's an example of using \code{optparse} in a simple script: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 20 | \begin{verbatim} |
| 21 | from optparse import OptionParser |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 22 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 23 | parser = OptionParser() |
| 24 | parser.add_option("-f", "--file", dest="filename", |
| 25 | help="write report to FILE", metavar="FILE") |
| 26 | parser.add_option("-q", "--quiet", |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 27 | action="store_false", dest="verbose", default=True, |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 28 | help="don't print status messages to stdout") |
| 29 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 30 | (options, args) = parser.parse_args() |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 31 | \end{verbatim} |
| 32 | |
| 33 | 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] | 34 | ``usual thing'' on the command-line, for example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 35 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 36 | <yourscript> --file=outfile -q |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 37 | \end{verbatim} |
| 38 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 39 | As it parses the command line, \code{optparse} sets attributes of the |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 40 | \code{options} object returned by \method{parse{\_}args()} based on user-supplied |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 41 | command-line values. When \method{parse{\_}args()} returns from parsing this |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 42 | command line, \code{options.filename} will be \code{"outfile"} and |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 43 | \code{options.verbose} will be \code{False}. \code{optparse} supports both long |
| 44 | and short options, allows short options to be merged together, and |
| 45 | allows options to be associated with their arguments in a variety of |
| 46 | ways. Thus, the following command lines are all equivalent to the above |
| 47 | example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 48 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 49 | <yourscript> -f outfile --quiet |
| 50 | <yourscript> --quiet --file outfile |
| 51 | <yourscript> -q -foutfile |
| 52 | <yourscript> -qfoutfile |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 53 | \end{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 54 | |
| 55 | Additionally, users can run one of |
| 56 | \begin{verbatim} |
| 57 | <yourscript> -h |
| 58 | <yourscript> --help |
| 59 | \end{verbatim} |
| 60 | |
| 61 | 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] | 62 | options: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 63 | \begin{verbatim} |
| 64 | usage: <yourscript> [options] |
| 65 | |
| 66 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 67 | -h, --help show this help message and exit |
| 68 | -f FILE, --file=FILE write report to FILE |
| 69 | -q, --quiet don't print status messages to stdout |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 70 | \end{verbatim} |
| 71 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 72 | where the value of \emph{yourscript} is determined at runtime (normally |
| 73 | from \code{sys.argv{[}0]}). |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 74 | % $Id: intro.txt 413 2004-09-28 00:59:13Z greg $ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 75 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 76 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 77 | \subsection{Background\label{optparse-background}} |
| 78 | |
| 79 | \module{optparse} was explicitly designed to encourage the creation of programs with |
| 80 | straightforward, conventional command-line interfaces. To that end, it |
| 81 | supports only the most common command-line syntax and semantics |
| 82 | conventionally used under \UNIX{}. If you are unfamiliar with these |
| 83 | conventions, read this section to acquaint yourself with them. |
| 84 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 85 | |
| 86 | \subsubsection{Terminology\label{optparse-terminology}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 87 | \begin{description} |
| 88 | \item[argument] |
| 89 | a string entered on the command-line, and passed by the shell to |
| 90 | \code{execl()} or \code{execv()}. In Python, arguments are elements of |
| 91 | \code{sys.argv{[}1:]} (\code{sys.argv{[}0]} is the name of the program being |
| 92 | executed). \UNIX{} shells also use the term ``word''. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 93 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 94 | It is occasionally desirable to substitute an argument list other |
| 95 | than \code{sys.argv{[}1:]}, so you should read ``argument'' as ``an element of |
| 96 | \code{sys.argv{[}1:]}, or of some other list provided as a substitute for |
| 97 | \code{sys.argv{[}1:]}''. |
| 98 | \item[option ] |
| 99 | an argument used to supply extra information to guide or customize the |
| 100 | execution of a program. There are many different syntaxes for |
| 101 | options; the traditional \UNIX{} syntax is a hyphen (``-'') followed by a |
| 102 | single letter, e.g. \code{"-x"} or \code{"-F"}. Also, traditional \UNIX{} |
| 103 | syntax allows multiple options to be merged into a single argument, |
| 104 | e.g. \code{"-x -F"} is equivalent to \code{"-xF"}. The GNU project |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 105 | introduced a double hyphen followed by a series of hyphen-separated words, |
| 106 | e.g. \longprogramopt{file} or \longprogramopt{dry-run}. These are the only two option |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 107 | syntaxes provided by \module{optparse}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 108 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 109 | Some other option syntaxes that the world has seen include: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 110 | \begin{itemize} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 111 | \item {} |
| 112 | a hyphen followed by a few letters, e.g. \code{"-pf"} (this is |
| 113 | \emph{not} the same as multiple options merged into a single argument) |
| 114 | |
| 115 | \item {} |
| 116 | a hyphen followed by a whole word, e.g. \code{"-file"} (this is |
| 117 | technically equivalent to the previous syntax, but they aren't |
| 118 | usually seen in the same program) |
| 119 | |
| 120 | \item {} |
| 121 | a plus sign followed by a single letter, or a few letters, |
| 122 | or a word, e.g. \code{"+f"}, \code{"+rgb"} |
| 123 | |
| 124 | \item {} |
| 125 | a slash followed by a letter, or a few letters, or a word, e.g. |
| 126 | \code{"/f"}, \code{"/file"} |
| 127 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 128 | \end{itemize} |
| 129 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 130 | These option syntaxes are not supported by \module{optparse}, and they never will |
| 131 | be. This is deliberate: the first three are non-standard on any |
| 132 | environment, and the last only makes sense if you're exclusively |
| 133 | targeting VMS, MS-DOS, and/or Windows. |
| 134 | \item[option argument] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 135 | an argument that follows an option, is closely associated with that |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 136 | option, and is consumed from the argument list when that option is. |
| 137 | With \module{optparse}, option arguments may either be in a separate argument |
| 138 | from their option: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 139 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 140 | -f foo |
| 141 | --file foo |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 142 | \end{verbatim} |
| 143 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 144 | or included in the same argument: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 145 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 146 | -ffoo |
| 147 | --file=foo |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 148 | \end{verbatim} |
| 149 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 150 | Typically, a given option either takes an argument or it doesn't. |
| 151 | Lots of people want an ``optional option arguments'' feature, meaning |
| 152 | that some options will take an argument if they see it, and won't if |
| 153 | they don't. This is somewhat controversial, because it makes parsing |
| 154 | ambiguous: if \code{"-a"} takes an optional argument and \code{"-b"} is |
| 155 | another option entirely, how do we interpret \code{"-ab"}? Because of |
| 156 | this ambiguity, \module{optparse} does not support this feature. |
| 157 | \item[positional argument] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 158 | something leftover in the argument list after options have been |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 159 | parsed, i.e. after options and their arguments have been parsed and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 160 | removed from the argument list. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 161 | \item[required option] |
| 162 | an option that must be supplied on the command-line; note that the |
| 163 | phrase ``required option'' is self-contradictory in English. \module{optparse} |
| 164 | doesn't prevent you from implementing required options, but doesn't |
| 165 | give you much help at it either. See \code{examples/required{\_}1.py} and |
| 166 | \code{examples/required{\_}2.py} in the \module{optparse} source distribution for two |
| 167 | ways to implement required options with \module{optparse}. |
| 168 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 169 | |
| 170 | For example, consider this hypothetical command-line: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 171 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 172 | prog -v --report /tmp/report.txt foo bar |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 173 | \end{verbatim} |
| 174 | |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 175 | \programopt{-v} and \longprogramopt{report} are both options. Assuming that |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 176 | \longprogramopt{report} takes one argument, \code{"/tmp/report.txt"} is an option |
| 177 | argument. \code{"foo"} and \code{"bar"} are positional arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 178 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 179 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 180 | \subsubsection{What are options for?\label{optparse-what-options-for}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 181 | |
| 182 | Options are used to provide extra information to tune or customize the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 183 | execution of a program. In case it wasn't clear, options are usually |
| 184 | \emph{optional}. A program should be able to run just fine with no options |
| 185 | whatsoever. (Pick a random program from the \UNIX{} or GNU toolsets. Can |
| 186 | it run without any options at all and still make sense? The main |
| 187 | exceptions are \code{find}, \code{tar}, and \code{dd}{---}all of which are mutant |
| 188 | oddballs that have been rightly criticized for their non-standard syntax |
| 189 | and confusing interfaces.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 190 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 191 | Lots of people want their programs to have ``required options''. Think |
| 192 | about it. If it's required, then it's \emph{not optional}! If there is a |
| 193 | piece of information that your program absolutely requires in order to |
| 194 | run successfully, that's what positional arguments are for. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 195 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 196 | As an example of good command-line interface design, consider the humble |
| 197 | \code{cp} utility, for copying files. It doesn't make much sense to try to |
| 198 | copy files without supplying a destination and at least one source. |
| 199 | Hence, \code{cp} fails if you run it with no arguments. However, it has a |
| 200 | flexible, useful syntax that does not require any options at all: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 201 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 202 | cp SOURCE DEST |
| 203 | cp SOURCE ... DEST-DIR |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 204 | \end{verbatim} |
| 205 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 206 | You can get pretty far with just that. Most \code{cp} implementations |
| 207 | provide a bunch of options to tweak exactly how the files are copied: |
| 208 | you can preserve mode and modification time, avoid following symlinks, |
| 209 | ask before clobbering existing files, etc. But none of this distracts |
| 210 | from the core mission of \code{cp}, which is to copy either one file to |
| 211 | another, or several files to another directory. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 212 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 213 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 214 | \subsubsection{What are positional arguments for?\label{optparse-what-positional-arguments-for}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 215 | |
| 216 | Positional arguments are for those pieces of information that your |
| 217 | program absolutely, positively requires to run. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 218 | |
| 219 | A good user interface should have as few absolute requirements as |
| 220 | possible. If your program requires 17 distinct pieces of information in |
| 221 | 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] | 222 | information from the user{---}most people will give up and walk away |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 223 | before they successfully run the program. This applies whether the user |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 224 | interface is a command-line, a configuration file, or a GUI: if you make |
| 225 | 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] | 226 | |
| 227 | In short, try to minimize the amount of information that users are |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 228 | absolutely required to supply{---}use sensible defaults whenever |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 229 | possible. Of course, you also want to make your programs reasonably |
| 230 | 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] | 231 | they are entries in a config file, widgets in the ``Preferences'' dialog |
| 232 | of a GUI, or command-line options{---}the more options you implement, the |
| 233 | more flexible your program is, and the more complicated its |
| 234 | implementation becomes. Too much flexibility has drawbacks as well, of |
| 235 | course; too many options can overwhelm users and make your code much |
| 236 | harder to maintain. |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 237 | % $Id: tao.txt 413 2004-09-28 00:59:13Z greg $ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 238 | |
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 | \subsection{Tutorial\label{optparse-tutorial}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 241 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 242 | While \module{optparse} is quite flexible and powerful, it's also straightforward to |
| 243 | use in most cases. This section covers the code patterns that are |
| 244 | common to any \module{optparse}-based program. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 245 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 246 | First, you need to import the OptionParser class; then, early in the |
| 247 | main program, create an OptionParser instance: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 248 | \begin{verbatim} |
| 249 | from optparse import OptionParser |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 250 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 251 | parser = OptionParser() |
| 252 | \end{verbatim} |
| 253 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 254 | Then you can start defining options. The basic syntax is: |
| 255 | \begin{verbatim} |
| 256 | parser.add_option(opt_str, ..., |
| 257 | attr=value, ...) |
| 258 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 259 | |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 260 | Each option has one or more option strings, such as \programopt{-f} or |
| 261 | \longprogramopt{file}, and several option attributes that tell \module{optparse} what to |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 262 | expect and what to do when it encounters that option on the command |
| 263 | line. |
| 264 | |
| 265 | Typically, each option will have one short option string and one long |
| 266 | option string, e.g.: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 267 | \begin{verbatim} |
| 268 | parser.add_option("-f", "--file", ...) |
| 269 | \end{verbatim} |
| 270 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 271 | You're free to define as many short option strings and as many long |
| 272 | option strings as you like (including zero), as long as there is at |
| 273 | least one option string overall. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 274 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 275 | The option strings passed to \method{add{\_}option()} are effectively labels for |
| 276 | the option defined by that call. For brevity, we will frequently refer |
| 277 | to \emph{encountering an option} on the command line; in reality, \module{optparse} |
| 278 | encounters \emph{option strings} and looks up options from them. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 279 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 280 | Once all of your options are defined, instruct \module{optparse} to parse your |
| 281 | program's command line: |
| 282 | \begin{verbatim} |
| 283 | (options, args) = parser.parse_args() |
| 284 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 285 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 286 | (If you like, you can pass a custom argument list to \method{parse{\_}args()}, |
| 287 | 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] | 288 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 289 | \method{parse{\_}args()} returns two values: |
| 290 | \begin{itemize} |
| 291 | \item {} |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 292 | \code{options}, an object containing values for all of your options{---}e.g. if \longprogramopt{file} takes a single string argument, then |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 293 | \code{options.file} will be the filename supplied by the user, or |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 294 | \code{None} if the user did not supply that option |
| 295 | |
| 296 | \item {} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 297 | \code{args}, the list of positional arguments leftover after parsing |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 298 | options |
| 299 | |
| 300 | \end{itemize} |
| 301 | |
| 302 | This tutorial section only covers the four most important option |
| 303 | attributes: \member{action}, \member{type}, \member{dest} (destination), and \member{help}. |
| 304 | Of these, \member{action} is the most fundamental. |
| 305 | |
| 306 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 307 | \subsubsection{Understanding option actions\label{optparse-understanding-option-actions}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 308 | |
| 309 | Actions tell \module{optparse} what to do when it encounters an option on the |
| 310 | command line. There is a fixed set of actions hard-coded into \module{optparse}; |
Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 311 | adding new actions is an advanced topic covered in section~\ref{optparse-extending-optparse}, Extending \module{optparse}. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 312 | Most actions tell \module{optparse} to store a value in some variable{---}for |
| 313 | example, take a string from the command line and store it in an |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 314 | attribute of \code{options}. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 315 | |
| 316 | If you don't specify an option action, \module{optparse} defaults to \code{store}. |
| 317 | |
| 318 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 319 | \subsubsection{The store action\label{optparse-store-action}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 320 | |
| 321 | The most common option action is \code{store}, which tells \module{optparse} to take |
| 322 | the next argument (or the remainder of the current argument), ensure |
| 323 | that it is of the correct type, and store it to your chosen destination. |
| 324 | |
| 325 | For example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 326 | \begin{verbatim} |
| 327 | parser.add_option("-f", "--file", |
| 328 | action="store", type="string", dest="filename") |
| 329 | \end{verbatim} |
| 330 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 331 | 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] | 332 | \begin{verbatim} |
| 333 | args = ["-f", "foo.txt"] |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 334 | (options, args) = parser.parse_args(args) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 335 | \end{verbatim} |
| 336 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 337 | When \module{optparse} sees the option string \code{"-f"}, it consumes the next |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 338 | argument, \code{"foo.txt"}, and stores it in \code{options.filename}. So, |
| 339 | after this call to \method{parse{\_}args()}, \code{options.filename} is |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 340 | \code{"foo.txt"}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 341 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 342 | Some other option types supported by \module{optparse} are \code{int} and \code{float}. |
| 343 | Here's an option that expects an integer argument: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 344 | \begin{verbatim} |
| 345 | parser.add_option("-n", type="int", dest="num") |
| 346 | \end{verbatim} |
| 347 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 348 | Note that this option has no long option string, which is perfectly |
| 349 | acceptable. Also, there's no explicit action, since the default is |
| 350 | \code{store}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 351 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 352 | Let's parse another fake command-line. This time, we'll jam the option |
| 353 | argument right up against the option: since \code{"-n42"} (one argument) is |
| 354 | equivalent to \code{"-n 42"} (two arguments), the code |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 355 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 356 | (options, args) = parser.parse_args(["-n42"]) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 357 | print options.num |
| 358 | \end{verbatim} |
| 359 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 360 | will print \code{"42"}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 361 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 362 | If you don't specify a type, \module{optparse} assumes \code{string}. Combined with the |
| 363 | fact that the default action is \code{store}, that means our first example |
| 364 | can be a lot shorter: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 365 | \begin{verbatim} |
| 366 | parser.add_option("-f", "--file", dest="filename") |
| 367 | \end{verbatim} |
| 368 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 369 | If you don't supply a destination, \module{optparse} figures out a sensible default |
| 370 | from the option strings: if the first long option string is |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 371 | \longprogramopt{foo-bar}, then the default destination is \code{foo{\_}bar}. If there |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 372 | are no long option strings, \module{optparse} looks at the first short option |
| 373 | string: the default destination for \code{"-f"} is \code{f}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 374 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 375 | \module{optparse} also includes built-in \code{long} and \code{complex} types. Adding |
Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 376 | types is covered in section~\ref{optparse-extending-optparse}, Extending \module{optparse}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 377 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 378 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 379 | \subsubsection{Handling boolean (flag) options\label{optparse-handling-boolean-options}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 380 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 381 | Flag options{---}set a variable to true or false when a particular option |
| 382 | is seen{---}are quite common. \module{optparse} supports them with two separate |
| 383 | actions, \code{store{\_}true} and \code{store{\_}false}. For example, you might have a |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 384 | \code{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] | 385 | \begin{verbatim} |
| 386 | parser.add_option("-v", action="store_true", dest="verbose") |
| 387 | parser.add_option("-q", action="store_false", dest="verbose") |
| 388 | \end{verbatim} |
| 389 | |
| 390 | Here we have two different options with the same destination, which is |
| 391 | perfectly OK. (It just means you have to be a bit careful when setting |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 392 | default values{---}see below.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 393 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 394 | When \module{optparse} encounters \code{"-v"} on the command line, it sets |
| 395 | \code{options.verbose} to \code{True}; when it encounters \code{"-q"}, |
| 396 | \code{options.verbose} is set to \code{False}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 397 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 398 | |
| 399 | \subsubsection{Other actions\label{optparse-other-actions}} |
| 400 | |
| 401 | Some other actions supported by \module{optparse} are: |
| 402 | \begin{description} |
| 403 | \item[\code{store{\_}const}] |
| 404 | store a constant value |
| 405 | \item[\code{append}] |
| 406 | append this option's argument to a list |
| 407 | \item[\code{count}] |
| 408 | increment a counter by one |
| 409 | \item[\code{callback}] |
| 410 | call a specified function |
| 411 | \end{description} |
| 412 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 413 | These are covered in section~\ref{optparse-reference-guide}, Reference Guide and section~\ref{optparse-option-callbacks}, Option Callbacks. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 414 | |
| 415 | |
| 416 | \subsubsection{Default values\label{optparse-default-values}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 417 | |
| 418 | All of the above examples involve setting some variable (the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 419 | ``destination'') when certain command-line options are seen. What happens |
| 420 | if those options are never seen? Since we didn't supply any defaults, |
| 421 | they are all set to \code{None}. This is usually fine, but sometimes you |
| 422 | want more control. \module{optparse} lets you supply a default value for each |
| 423 | destination, which is assigned before the command line is parsed. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 424 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 425 | First, consider the verbose/quiet example. If we want \module{optparse} to set |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 426 | \code{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] | 427 | \begin{verbatim} |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 428 | parser.add_option("-v", action="store_true", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 429 | parser.add_option("-q", action="store_false", dest="verbose") |
| 430 | \end{verbatim} |
| 431 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 432 | Since default values apply to the \emph{destination} rather than to any |
| 433 | particular option, and these two options happen to have the same |
| 434 | destination, this is exactly equivalent: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 435 | \begin{verbatim} |
| 436 | parser.add_option("-v", action="store_true", dest="verbose") |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 437 | parser.add_option("-q", action="store_false", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 438 | \end{verbatim} |
| 439 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 440 | Consider this: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 441 | \begin{verbatim} |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 442 | parser.add_option("-v", action="store_true", dest="verbose", default=False) |
| 443 | parser.add_option("-q", action="store_false", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 444 | \end{verbatim} |
| 445 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 446 | Again, the default value for \code{verbose} will be \code{True}: the last |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 447 | default value supplied for any particular destination is the one that |
| 448 | counts. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 449 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 450 | A clearer way to specify default values is the \method{set{\_}defaults()} |
| 451 | method of OptionParser, which you can call at any time before calling |
| 452 | \method{parse{\_}args()}: |
| 453 | \begin{verbatim} |
| 454 | parser.set_defaults(verbose=True) |
| 455 | parser.add_option(...) |
| 456 | (options, args) = parser.parse_args() |
| 457 | \end{verbatim} |
| 458 | |
| 459 | As before, the last value specified for a given option destination is |
| 460 | the one that counts. For clarity, try to use one method or the other of |
| 461 | setting default values, not both. |
| 462 | |
| 463 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 464 | \subsubsection{Generating help\label{optparse-generating-help}} |
| 465 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 466 | \module{optparse}'s ability to generate help and usage text automatically is useful |
| 467 | for creating user-friendly command-line interfaces. All you have to do |
| 468 | is supply a \member{help} value for each option, and optionally a short usage |
| 469 | message for your whole program. Here's an OptionParser populated with |
| 470 | user-friendly (documented) options: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 471 | \begin{verbatim} |
| 472 | usage = "usage: %prog [options] arg1 arg2" |
| 473 | parser = OptionParser(usage=usage) |
| 474 | parser.add_option("-v", "--verbose", |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 475 | action="store_true", dest="verbose", default=True, |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 476 | help="make lots of noise [default]") |
| 477 | parser.add_option("-q", "--quiet", |
| 478 | action="store_false", dest="verbose", |
| 479 | help="be vewwy quiet (I'm hunting wabbits)") |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 480 | parser.add_option("-f", "--filename", |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 481 | metavar="FILE", help="write output to FILE"), |
| 482 | parser.add_option("-m", "--mode", |
| 483 | default="intermediate", |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 484 | help="interaction mode: novice, intermediate, " |
| 485 | "or expert [default: %default]") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 486 | \end{verbatim} |
| 487 | |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 488 | If \module{optparse} encounters either \programopt{-h} or \longprogramopt{help} on the command-line, |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 489 | or if you just call \method{parser.print{\_}help()}, it prints the following to |
| 490 | standard output: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 491 | \begin{verbatim} |
| 492 | usage: <yourscript> [options] arg1 arg2 |
| 493 | |
| 494 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 495 | -h, --help show this help message and exit |
| 496 | -v, --verbose make lots of noise [default] |
| 497 | -q, --quiet be vewwy quiet (I'm hunting wabbits) |
| 498 | -f FILE, --filename=FILE |
| 499 | write output to FILE |
| 500 | -m MODE, --mode=MODE interaction mode: novice, intermediate, or |
| 501 | expert [default: intermediate] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 502 | \end{verbatim} |
| 503 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 504 | (If the help output is triggered by a help option, \module{optparse} exits after |
| 505 | printing the help text.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 506 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 507 | There's a lot going on here to help \module{optparse} generate the best possible |
| 508 | help message: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 509 | \begin{itemize} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 510 | \item {} |
| 511 | the script defines its own usage message: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 512 | \begin{verbatim} |
| 513 | usage = "usage: %prog [options] arg1 arg2" |
| 514 | \end{verbatim} |
| 515 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 516 | \module{optparse} expands \code{"{\%}prog"} in the usage string to the name of the current |
| 517 | program, i.e. \code{os.path.basename(sys.argv{[}0])}. The expanded string |
| 518 | is then printed before the detailed option help. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 519 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 520 | If you don't supply a usage string, \module{optparse} uses a bland but sensible |
| 521 | default: ``\code{usage: {\%}prog {[}options]"}, which is fine if your script |
| 522 | doesn't take any positional arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 523 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 524 | \item {} |
| 525 | every option defines a help string, and doesn't worry about line- |
| 526 | wrapping{---}\module{optparse} takes care of wrapping lines and making the |
| 527 | help output look good. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 528 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 529 | \item {} |
| 530 | options that take a value indicate this fact in their |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 531 | automatically-generated help message, e.g. for the ``mode'' option: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 532 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 533 | -m MODE, --mode=MODE |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 534 | \end{verbatim} |
| 535 | |
| 536 | Here, ``MODE'' is called the meta-variable: it stands for the argument |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 537 | that the user is expected to supply to \programopt{-m}/\longprogramopt{mode}. By default, |
| 538 | \module{optparse} converts the destination variable name to uppercase and uses |
| 539 | that for the meta-variable. Sometimes, that's not what you want{---}for example, the \longprogramopt{filename} option explicitly sets |
| 540 | \code{metavar="FILE"}, resulting in this automatically-generated option |
| 541 | description: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 542 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 543 | -f FILE, --filename=FILE |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 544 | \end{verbatim} |
| 545 | |
| 546 | This is important for more than just saving space, though: the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 547 | manually written help text uses the meta-variable ``FILE'' to clue the |
| 548 | user in that there's a connection between the semi-formal syntax ``-f |
| 549 | FILE'' and the informal semantic description ``write output to FILE''. |
| 550 | This is a simple but effective way to make your help text a lot |
| 551 | clearer and more useful for end users. |
| 552 | |
| 553 | \item {} |
| 554 | options that have a default value can include \code{{\%}default} in |
| 555 | the help string{---}\module{optparse} will replace it with \function{str()} of the |
| 556 | option's default value. If an option has no default value (or the |
| 557 | default value is \code{None}), \code{{\%}default} expands to \code{none}. |
| 558 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 559 | \end{itemize} |
| 560 | |
Andrew M. Kuchling | af81c57 | 2008-01-19 21:01:39 +0000 | [diff] [blame] | 561 | When dealing with many options, it is convenient to group these |
| 562 | options for better help output. An \class{OptionParser} can contain |
| 563 | several option groups, each of which can contain several options. |
| 564 | |
| 565 | Continuing with the parser defined above, adding an |
| 566 | \class{OptionGroup} to a parser is easy: |
| 567 | |
| 568 | \begin{verbatim} |
| 569 | group = OptionGroup(parser, ``Dangerous Options'', |
| 570 | ``Caution: use these options at your own risk. `` |
| 571 | ``It is believed that some of them bite.'') |
| 572 | group.add_option(``-g'', action=''store_true'', help=''Group option.'') |
| 573 | parser.add_option_group(group) |
| 574 | \end{verbatim} |
| 575 | |
| 576 | This would result in the following help output: |
| 577 | |
| 578 | \begin{verbatim} |
| 579 | usage: [options] arg1 arg2 |
| 580 | |
| 581 | options: |
| 582 | -h, --help show this help message and exit |
| 583 | -v, --verbose make lots of noise [default] |
| 584 | -q, --quiet be vewwy quiet (I'm hunting wabbits) |
| 585 | -fFILE, --file=FILE write output to FILE |
| 586 | -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate' |
| 587 | [default], 'expert' |
| 588 | |
| 589 | Dangerous Options: |
| 590 | Caution: use of these options is at your own risk. It is believed that |
| 591 | some of them bite. |
| 592 | -g Group option. |
| 593 | \end{verbatim} |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 594 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 595 | \subsubsection{Printing a version string\label{optparse-printing-version-string}} |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 596 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 597 | Similar to the brief usage string, \module{optparse} can also print a version string |
| 598 | for your program. You have to supply the string as the \code{version} |
| 599 | argument to OptionParser: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 600 | \begin{verbatim} |
| 601 | parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") |
| 602 | \end{verbatim} |
| 603 | |
Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 604 | \code{"{\%}prog"} is expanded just like it is in \code{usage}. Apart |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 605 | from that, \code{version} can contain anything you like. When you supply |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 606 | it, \module{optparse} automatically adds a \longprogramopt{version} option to your parser. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 607 | If it encounters this option on the command line, it expands your |
| 608 | \code{version} string (by replacing \code{"{\%}prog"}), prints it to stdout, and |
| 609 | exits. |
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 | For example, if your script is called \code{/usr/bin/foo}: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 612 | \begin{verbatim} |
| 613 | $ /usr/bin/foo --version |
| 614 | foo 1.0 |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 615 | \end{verbatim} |
| 616 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 617 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 618 | \subsubsection{How \module{optparse} handles errors\label{optparse-how-optparse-handles-errors}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 619 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 620 | There are two broad classes of errors that \module{optparse} has to worry about: |
| 621 | programmer errors and user errors. Programmer errors are usually |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 622 | erroneous calls to \code{parser.add{\_}option()}, e.g. invalid option strings, |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 623 | unknown option attributes, missing option attributes, etc. These are |
| 624 | dealt with in the usual way: raise an exception (either |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 625 | \code{optparse.OptionError} or \code{TypeError}) and let the program crash. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 626 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 627 | Handling user errors is much more important, since they are guaranteed |
| 628 | to happen no matter how stable your code is. \module{optparse} can automatically |
| 629 | detect some user errors, such as bad option arguments (passing \code{"-n |
| 630 | 4x"} where \programopt{-n} takes an integer argument), missing arguments |
| 631 | (\code{"-n"} at the end of the command line, where \programopt{-n} takes an argument |
| 632 | of any type). Also, you can call \code{parser.error()} to signal an |
| 633 | application-defined error condition: |
| 634 | \begin{verbatim} |
| 635 | (options, args) = parser.parse_args() |
| 636 | [...] |
| 637 | if options.a and options.b: |
| 638 | parser.error("options -a and -b are mutually exclusive") |
| 639 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 640 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 641 | In either case, \module{optparse} handles the error the same way: it prints the |
| 642 | program's usage message and an error message to standard error and |
| 643 | exits with error status 2. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 644 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 645 | Consider the first example above, where the user passes \code{"4x"} to an |
| 646 | option that takes an integer: |
| 647 | \begin{verbatim} |
| 648 | $ /usr/bin/foo -n 4x |
| 649 | usage: foo [options] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 650 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 651 | foo: error: option -n: invalid integer value: '4x' |
| 652 | \end{verbatim} |
| 653 | |
| 654 | Or, where the user fails to pass a value at all: |
| 655 | \begin{verbatim} |
| 656 | $ /usr/bin/foo -n |
| 657 | usage: foo [options] |
| 658 | |
| 659 | foo: error: -n option requires an argument |
| 660 | \end{verbatim} |
| 661 | |
| 662 | \module{optparse}-generated error messages take care always to mention the option |
| 663 | involved in the error; be sure to do the same when calling |
| 664 | \code{parser.error()} from your application code. |
| 665 | |
| 666 | If \module{optparse}'s default error-handling behaviour does not suite your needs, |
| 667 | you'll need to subclass OptionParser and override \code{exit()} and/or |
| 668 | \method{error()}. |
| 669 | |
| 670 | |
| 671 | \subsubsection{Putting it all together\label{optparse-putting-it-all-together}} |
| 672 | |
| 673 | Here's what \module{optparse}-based scripts usually look like: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 674 | \begin{verbatim} |
| 675 | from optparse import OptionParser |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 676 | [...] |
| 677 | def main(): |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 678 | usage = "usage: %prog [options] arg" |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 679 | parser = OptionParser(usage) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 680 | parser.add_option("-f", "--file", dest="filename", |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 681 | help="read data from FILENAME") |
| 682 | parser.add_option("-v", "--verbose", |
| 683 | action="store_true", dest="verbose") |
| 684 | parser.add_option("-q", "--quiet", |
| 685 | action="store_false", dest="verbose") |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 686 | [...] |
| 687 | (options, args) = parser.parse_args() |
| 688 | if len(args) != 1: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 689 | parser.error("incorrect number of arguments") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 690 | if options.verbose: |
Johannes Gijsbers | c9c37ca | 2004-09-11 15:47:30 +0000 | [diff] [blame] | 691 | print "reading %s..." % options.filename |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 692 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 693 | |
| 694 | if __name__ == "__main__": |
| 695 | main() |
| 696 | \end{verbatim} |
Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 697 | % $Id: tutorial.txt 515 2006-06-10 15:37:45Z gward $ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 698 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 699 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 700 | \subsection{Reference Guide\label{optparse-reference-guide}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 701 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 702 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 703 | \subsubsection{Creating the parser\label{optparse-creating-parser}} |
| 704 | |
| 705 | The first step in using \module{optparse} is to create an OptionParser instance: |
| 706 | \begin{verbatim} |
| 707 | parser = OptionParser(...) |
| 708 | \end{verbatim} |
| 709 | |
| 710 | The OptionParser constructor has no required arguments, but a number of |
| 711 | optional keyword arguments. You should always pass them as keyword |
| 712 | arguments, i.e. do not rely on the order in which the arguments are |
| 713 | declared. |
| 714 | \begin{quote} |
| 715 | \begin{description} |
| 716 | \item[\code{usage} (default: \code{"{\%}prog {[}options]"})] |
| 717 | The usage summary to print when your program is run incorrectly or |
| 718 | with a help option. When \module{optparse} prints the usage string, it expands |
| 719 | \code{{\%}prog} to \code{os.path.basename(sys.argv{[}0])} (or to \code{prog} if |
| 720 | you passed that keyword argument). To suppress a usage message, |
| 721 | pass the special value \code{optparse.SUPPRESS{\_}USAGE}. |
| 722 | \item[\code{option{\_}list} (default: \code{{[}]})] |
| 723 | A list of Option objects to populate the parser with. The options |
| 724 | in \code{option{\_}list} are added after any options in |
| 725 | \code{standard{\_}option{\_}list} (a class attribute that may be set by |
| 726 | OptionParser subclasses), but before any version or help options. |
| 727 | Deprecated; use \method{add{\_}option()} after creating the parser instead. |
| 728 | \item[\code{option{\_}class} (default: optparse.Option)] |
| 729 | Class to use when adding options to the parser in \method{add{\_}option()}. |
| 730 | \item[\code{version} (default: \code{None})] |
| 731 | A version string to print when the user supplies a version option. |
| 732 | If you supply a true value for \code{version}, \module{optparse} automatically adds |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 733 | a version option with the single option string \longprogramopt{version}. The |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 734 | substring \code{"{\%}prog"} is expanded the same as for \code{usage}. |
| 735 | \item[\code{conflict{\_}handler} (default: \code{"error"})] |
| 736 | Specifies what to do when options with conflicting option strings |
| 737 | are added to the parser; see section~\ref{optparse-conflicts-between-options}, Conflicts between options. |
| 738 | \item[\code{description} (default: \code{None})] |
| 739 | A paragraph of text giving a brief overview of your program. \module{optparse} |
| 740 | reformats this paragraph to fit the current terminal width and |
| 741 | prints it when the user requests help (after \code{usage}, but before |
| 742 | the list of options). |
| 743 | \item[\code{formatter} (default: a new IndentedHelpFormatter)] |
| 744 | An instance of optparse.HelpFormatter that will be used for |
| 745 | printing help text. \module{optparse} provides two concrete classes for this |
| 746 | purpose: IndentedHelpFormatter and TitledHelpFormatter. |
| 747 | \item[\code{add{\_}help{\_}option} (default: \code{True})] |
| 748 | If true, \module{optparse} will add a help option (with option strings \code{"-h"} |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 749 | and \longprogramopt{help}) to the parser. |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 750 | \item[\code{prog}] |
| 751 | The string to use when expanding \code{"{\%}prog"} in \code{usage} and |
| 752 | \code{version} instead of \code{os.path.basename(sys.argv{[}0])}. |
| 753 | \end{description} |
| 754 | \end{quote} |
| 755 | |
| 756 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 757 | \subsubsection{Populating the parser\label{optparse-populating-parser}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 758 | |
| 759 | There are several ways to populate the parser with options. The |
| 760 | preferred way is by using \code{OptionParser.add{\_}option()}, as shown in |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 761 | section~\ref{optparse-tutorial}, the tutorial. \method{add{\_}option()} can be called in one of two |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 762 | ways: |
| 763 | \begin{itemize} |
| 764 | \item {} |
| 765 | pass it an Option instance (as returned by \function{make{\_}option()}) |
| 766 | |
| 767 | \item {} |
| 768 | pass it any combination of positional and keyword arguments that are |
| 769 | acceptable to \function{make{\_}option()} (i.e., to the Option constructor), |
| 770 | and it will create the Option instance for you |
| 771 | |
| 772 | \end{itemize} |
| 773 | |
| 774 | The other alternative is to pass a list of pre-constructed Option |
| 775 | instances to the OptionParser constructor, as in: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 776 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 777 | option_list = [ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 778 | make_option("-f", "--filename", |
| 779 | action="store", type="string", dest="filename"), |
| 780 | make_option("-q", "--quiet", |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 781 | action="store_false", dest="verbose"), |
| 782 | ] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 783 | parser = OptionParser(option_list=option_list) |
| 784 | \end{verbatim} |
| 785 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 786 | (\function{make{\_}option()} is a factory function for creating Option instances; |
| 787 | currently it is an alias for the Option constructor. A future version |
| 788 | of \module{optparse} may split Option into several classes, and \function{make{\_}option()} |
| 789 | will pick the right class to instantiate. Do not instantiate Option |
| 790 | directly.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 791 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 792 | |
| 793 | \subsubsection{Defining options\label{optparse-defining-options}} |
| 794 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 795 | Each Option instance represents a set of synonymous command-line option |
Greg Ward | 961eda7 | 2004-11-12 01:20:17 +0000 | [diff] [blame] | 796 | strings, e.g. \programopt{-f} and \longprogramopt{file}. You can |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 797 | specify any number of short or long option strings, but you must specify |
| 798 | at least one overall option string. |
| 799 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 800 | The canonical way to create an Option instance is with the |
| 801 | \method{add{\_}option()} method of \class{OptionParser}: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 802 | \begin{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 803 | parser.add_option(opt_str[, ...], attr=value, ...) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 804 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 805 | |
| 806 | To define an option with only a short option string: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 807 | \begin{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 808 | parser.add_option("-f", attr=value, ...) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 809 | \end{verbatim} |
| 810 | |
| 811 | And to define an option with only a long option string: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 812 | \begin{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 813 | parser.add_option("--foo", attr=value, ...) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 814 | \end{verbatim} |
| 815 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 816 | The keyword arguments define attributes of the new Option object. The |
| 817 | most important option attribute is \member{action}, and it largely determines |
| 818 | which other attributes are relevant or required. If you pass irrelevant |
| 819 | option attributes, or fail to pass required ones, \module{optparse} raises an |
| 820 | OptionError exception explaining your mistake. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 821 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 822 | An options's \emph{action} determines what \module{optparse} does when it encounters this |
| 823 | option on the command-line. The standard option actions hard-coded into |
| 824 | \module{optparse} are: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 825 | \begin{description} |
| 826 | \item[\code{store}] |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 827 | store this option's argument (default) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 828 | \item[\code{store{\_}const}] |
| 829 | store a constant value |
| 830 | \item[\code{store{\_}true}] |
| 831 | store a true value |
| 832 | \item[\code{store{\_}false}] |
| 833 | store a false value |
| 834 | \item[\code{append}] |
| 835 | append this option's argument to a list |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 836 | \item[\code{append{\_}const}] |
| 837 | append a constant value to a list |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 838 | \item[\code{count}] |
| 839 | increment a counter by one |
| 840 | \item[\code{callback}] |
| 841 | call a specified function |
| 842 | \item[\member{help}] |
| 843 | print a usage message including all options and the |
| 844 | documentation for them |
| 845 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 846 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 847 | (If you don't supply an action, the default is \code{store}. For this |
| 848 | 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] | 849 | below.) |
| 850 | |
| 851 | As you can see, most actions involve storing or updating a value |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 852 | somewhere. \module{optparse} always creates a special object for this, |
| 853 | conventionally called \code{options} (it happens to be an instance of |
| 854 | \code{optparse.Values}). Option arguments (and various other values) are |
| 855 | stored as attributes of this object, according to the \member{dest} |
| 856 | (destination) option attribute. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 857 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 858 | For example, when you call |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 859 | \begin{verbatim} |
| 860 | parser.parse_args() |
| 861 | \end{verbatim} |
| 862 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 863 | one of the first things \module{optparse} does is create the \code{options} object: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 864 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 865 | options = Values() |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 866 | \end{verbatim} |
| 867 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 868 | If one of the options in this parser is defined with |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 869 | \begin{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 870 | parser.add_option("-f", "--file", action="store", type="string", dest="filename") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 871 | \end{verbatim} |
| 872 | |
| 873 | and the command-line being parsed includes any of the following: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 874 | \begin{verbatim} |
| 875 | -ffoo |
| 876 | -f foo |
| 877 | --file=foo |
| 878 | --file foo |
| 879 | \end{verbatim} |
| 880 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 881 | then \module{optparse}, on seeing this option, will do the equivalent of |
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 | options.filename = "foo" |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 884 | \end{verbatim} |
| 885 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 886 | The \member{type} and \member{dest} option attributes are almost as important as |
| 887 | \member{action}, but \member{action} is the only one that makes sense for \emph{all} |
| 888 | options. |
| 889 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 890 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 891 | \subsubsection{Standard option actions\label{optparse-standard-option-actions}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 892 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 893 | The various option actions all have slightly different requirements and |
| 894 | effects. Most actions have several relevant option attributes which you |
| 895 | may specify to guide \module{optparse}'s behaviour; a few have required attributes, |
| 896 | which you must specify for any option using that action. |
| 897 | \begin{itemize} |
| 898 | \item {} |
| 899 | \code{store} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 900 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 901 | The option must be followed by an argument, which is |
| 902 | converted to a value according to \member{type} and stored in |
| 903 | \member{dest}. If \code{nargs} {\textgreater} 1, multiple arguments will be consumed |
| 904 | from the command line; all will be converted according to |
| 905 | \member{type} and stored to \member{dest} as a tuple. See the ``Option |
| 906 | types'' section below. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 907 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 908 | If \code{choices} is supplied (a list or tuple of strings), the type |
| 909 | defaults to \code{choice}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 910 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 911 | If \member{type} is not supplied, it defaults to \code{string}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 912 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 913 | If \member{dest} is not supplied, \module{optparse} derives a destination from the |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 914 | first long option string (e.g., \longprogramopt{foo-bar} implies \code{foo{\_}bar}). |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 915 | If there are no long option strings, \module{optparse} derives a destination from |
| 916 | the first short option string (e.g., \code{"-f"} implies \code{f}). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 917 | |
| 918 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 919 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 920 | parser.add_option("-f") |
| 921 | parser.add_option("-p", type="float", nargs=3, dest="point") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 922 | \end{verbatim} |
| 923 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 924 | As it parses the command line |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 925 | \begin{verbatim} |
| 926 | -f foo.txt -p 1 -3.5 4 -fbar.txt |
| 927 | \end{verbatim} |
| 928 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 929 | \module{optparse} will set |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 930 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 931 | options.f = "foo.txt" |
| 932 | options.point = (1.0, -3.5, 4.0) |
| 933 | options.f = "bar.txt" |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 934 | \end{verbatim} |
| 935 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 936 | \item {} |
| 937 | \code{store{\_}const} {[}required: \code{const}; relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 938 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 939 | The value \code{const} is stored in \member{dest}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 940 | |
| 941 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 942 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 943 | parser.add_option("-q", "--quiet", |
| 944 | action="store_const", const=0, dest="verbose") |
| 945 | parser.add_option("-v", "--verbose", |
| 946 | action="store_const", const=1, dest="verbose") |
| 947 | parser.add_option("--noisy", |
| 948 | action="store_const", const=2, dest="verbose") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 949 | \end{verbatim} |
| 950 | |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 951 | If \longprogramopt{noisy} is seen, \module{optparse} will set |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 952 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 953 | options.verbose = 2 |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 954 | \end{verbatim} |
| 955 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 956 | \item {} |
| 957 | \code{store{\_}true} {[}relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 958 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 959 | A special case of \code{store{\_}const} that stores a true value |
| 960 | to \member{dest}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 961 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 962 | \item {} |
| 963 | \code{store{\_}false} {[}relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 964 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 965 | Like \code{store{\_}true}, but stores a false value. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 966 | |
| 967 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 968 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 969 | parser.add_option("--clobber", action="store_true", dest="clobber") |
| 970 | parser.add_option("--no-clobber", action="store_false", dest="clobber") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 971 | \end{verbatim} |
| 972 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 973 | \item {} |
| 974 | \code{append} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 975 | |
| 976 | 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] | 977 | list in \member{dest}. If no default value for \member{dest} is supplied, an |
| 978 | empty list is automatically created when \module{optparse} first encounters this |
| 979 | option on the command-line. If \code{nargs} {\textgreater} 1, multiple arguments are |
| 980 | 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] | 981 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 982 | The defaults for \member{type} and \member{dest} are the same as for the |
| 983 | \code{store} action. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 984 | |
| 985 | Example: |
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 | parser.add_option("-t", "--tracks", action="append", type="int") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 988 | \end{verbatim} |
| 989 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 990 | 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] | 991 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 992 | options.tracks = [] |
| 993 | options.tracks.append(int("3")) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 994 | \end{verbatim} |
| 995 | |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 996 | If, a little later on, \longprogramopt{tracks=4} is seen, it does: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 997 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 998 | options.tracks.append(int("4")) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 999 | \end{verbatim} |
| 1000 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1001 | \item {} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1002 | \code{append{\_}const} {[}required: \code{const}; relevant: \member{dest}] |
| 1003 | |
| 1004 | Like \code{store{\_}const}, but the value \code{const} is appended to \member{dest}; |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1005 | as with \code{append}, \member{dest} defaults to \code{None}, and an empty list is |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1006 | automatically created the first time the option is encountered. |
| 1007 | |
| 1008 | \item {} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1009 | \code{count} {[}relevant: \member{dest}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1010 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1011 | Increment the integer stored at \member{dest}. If no default value is |
| 1012 | supplied, \member{dest} is set to zero before being incremented the first |
| 1013 | time. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1014 | |
| 1015 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1016 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1017 | parser.add_option("-v", action="count", dest="verbosity") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1018 | \end{verbatim} |
| 1019 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1020 | The first time \code{"-v"} is seen on the command line, \module{optparse} does the |
| 1021 | equivalent of: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1022 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1023 | options.verbosity = 0 |
| 1024 | options.verbosity += 1 |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1025 | \end{verbatim} |
| 1026 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1027 | Every subsequent occurrence of \code{"-v"} results in |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1028 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1029 | options.verbosity += 1 |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1030 | \end{verbatim} |
| 1031 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1032 | \item {} |
| 1033 | \code{callback} {[}required: \code{callback}; |
| 1034 | relevant: \member{type}, \code{nargs}, \code{callback{\_}args}, \code{callback{\_}kwargs}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1035 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1036 | Call the function specified by \code{callback}, which is called as |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1037 | \begin{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1038 | func(option, opt_str, value, parser, *args, **kwargs) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1039 | \end{verbatim} |
| 1040 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1041 | See section~\ref{optparse-option-callbacks}, Option Callbacks for more detail. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1042 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1043 | \item {} |
| 1044 | \member{help} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1045 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1046 | Prints a complete help message for all the options in the |
| 1047 | current option parser. The help message is constructed from |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1048 | the \code{usage} string passed to OptionParser's constructor and |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1049 | the \member{help} string passed to every option. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1050 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1051 | If no \member{help} string is supplied for an option, it will still be |
| 1052 | listed in the help message. To omit an option entirely, use |
| 1053 | the special value \code{optparse.SUPPRESS{\_}HELP}. |
| 1054 | |
| 1055 | \module{optparse} automatically adds a \member{help} option to all OptionParsers, so |
| 1056 | you do not normally need to create one. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1057 | |
| 1058 | Example: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1059 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1060 | from optparse import OptionParser, SUPPRESS_HELP |
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 | parser = OptionParser() |
| 1063 | parser.add_option("-h", "--help", action="help"), |
| 1064 | parser.add_option("-v", action="store_true", dest="verbose", |
| 1065 | help="Be moderately verbose") |
| 1066 | parser.add_option("--file", dest="filename", |
| 1067 | help="Input file to read data from"), |
| 1068 | parser.add_option("--secret", help=SUPPRESS_HELP) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1069 | \end{verbatim} |
| 1070 | |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1071 | If \module{optparse} sees either \programopt{h} or \longprogramopt{help} on the command line, it |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1072 | will print something like the following help message to stdout |
| 1073 | (assuming \code{sys.argv{[}0]} is \code{"foo.py"}): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1074 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1075 | usage: foo.py [options] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1076 | |
| 1077 | options: |
| 1078 | -h, --help Show this help message and exit |
| 1079 | -v Be moderately verbose |
| 1080 | --file=FILENAME Input file to read data from |
| 1081 | \end{verbatim} |
| 1082 | |
| 1083 | After printing the help message, \module{optparse} terminates your process |
| 1084 | with \code{sys.exit(0)}. |
| 1085 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1086 | \item {} |
| 1087 | \code{version} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1088 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1089 | Prints the version number supplied to the OptionParser to stdout and |
| 1090 | exits. The version number is actually formatted and printed by the |
| 1091 | \code{print{\_}version()} method of OptionParser. Generally only relevant |
| 1092 | if the \code{version} argument is supplied to the OptionParser |
| 1093 | constructor. As with \member{help} options, you will rarely create |
| 1094 | \code{version} options, since \module{optparse} automatically adds them when needed. |
| 1095 | |
| 1096 | \end{itemize} |
| 1097 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1098 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1099 | \subsubsection{Option attributes\label{optparse-option-attributes}} |
| 1100 | |
| 1101 | The following option attributes may be passed as keyword arguments |
| 1102 | to \code{parser.add{\_}option()}. If you pass an option attribute |
| 1103 | that is not relevant to a particular option, or fail to pass a required |
| 1104 | option attribute, \module{optparse} raises OptionError. |
| 1105 | \begin{itemize} |
| 1106 | \item {} |
| 1107 | \member{action} (default: \code{"store"}) |
| 1108 | |
| 1109 | Determines \module{optparse}'s behaviour when this option is seen on the command |
| 1110 | line; the available options are documented above. |
| 1111 | |
| 1112 | \item {} |
| 1113 | \member{type} (default: \code{"string"}) |
| 1114 | |
| 1115 | The argument type expected by this option (e.g., \code{"string"} or |
| 1116 | \code{"int"}); the available option types are documented below. |
| 1117 | |
| 1118 | \item {} |
| 1119 | \member{dest} (default: derived from option strings) |
| 1120 | |
| 1121 | If the option's action implies writing or modifying a value somewhere, |
| 1122 | this tells \module{optparse} where to write it: \member{dest} names an attribute of the |
| 1123 | \code{options} object that \module{optparse} builds as it parses the command line. |
| 1124 | |
| 1125 | \item {} |
| 1126 | \code{default} (deprecated) |
| 1127 | |
| 1128 | The value to use for this option's destination if the option is not |
| 1129 | seen on the command line. Deprecated; use \code{parser.set{\_}defaults()} |
| 1130 | instead. |
| 1131 | |
| 1132 | \item {} |
| 1133 | \code{nargs} (default: 1) |
| 1134 | |
| 1135 | How many arguments of type \member{type} should be consumed when this |
| 1136 | option is seen. If {\textgreater} 1, \module{optparse} will store a tuple of values to |
| 1137 | \member{dest}. |
| 1138 | |
| 1139 | \item {} |
| 1140 | \code{const} |
| 1141 | |
| 1142 | For actions that store a constant value, the constant value to store. |
| 1143 | |
| 1144 | \item {} |
| 1145 | \code{choices} |
| 1146 | |
| 1147 | For options of type \code{"choice"}, the list of strings the user |
| 1148 | may choose from. |
| 1149 | |
| 1150 | \item {} |
| 1151 | \code{callback} |
| 1152 | |
| 1153 | For options with action \code{"callback"}, the callable to call when this |
| 1154 | option is seen. See section~\ref{optparse-option-callbacks}, Option Callbacks for detail on the arguments |
| 1155 | passed to \code{callable}. |
| 1156 | |
| 1157 | \item {} |
| 1158 | \code{callback{\_}args}, \code{callback{\_}kwargs} |
| 1159 | |
| 1160 | Additional positional and keyword arguments to pass to \code{callback} |
| 1161 | after the four standard callback arguments. |
| 1162 | |
| 1163 | \item {} |
| 1164 | \member{help} |
| 1165 | |
| 1166 | Help text to print for this option when listing all available options |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1167 | after the user supplies a \member{help} option (such as \longprogramopt{help}). |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1168 | If no help text is supplied, the option will be listed without help |
| 1169 | text. To hide this option, use the special value \code{SUPPRESS{\_}HELP}. |
| 1170 | |
| 1171 | \item {} |
| 1172 | \code{metavar} (default: derived from option strings) |
| 1173 | |
| 1174 | Stand-in for the option argument(s) to use when printing help text. |
| 1175 | See section~\ref{optparse-tutorial}, the tutorial for an example. |
| 1176 | |
| 1177 | \end{itemize} |
| 1178 | |
| 1179 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1180 | \subsubsection{Standard option types\label{optparse-standard-option-types}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1181 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1182 | \module{optparse} has six built-in option types: \code{string}, \code{int}, \code{long}, |
| 1183 | \code{choice}, \code{float} and \code{complex}. If you need to add new option |
Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 1184 | types, see section~\ref{optparse-extending-optparse}, Extending \module{optparse}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1185 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1186 | Arguments to string options are not checked or converted in any way: the |
| 1187 | text on the command line is stored in the destination (or passed to the |
| 1188 | callback) as-is. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1189 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1190 | Integer arguments (type \code{int} or \code{long}) are parsed as follows: |
| 1191 | \begin{quote} |
| 1192 | \begin{itemize} |
| 1193 | \item {} |
| 1194 | if the number starts with \code{0x}, it is parsed as a hexadecimal number |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1195 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1196 | \item {} |
| 1197 | if the number starts with \code{0}, it is parsed as an octal number |
| 1198 | |
| 1199 | \item {} |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1200 | if the number starts with \code{0b}, it is parsed as a binary number |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1201 | |
| 1202 | \item {} |
| 1203 | otherwise, the number is parsed as a decimal number |
| 1204 | |
| 1205 | \end{itemize} |
| 1206 | \end{quote} |
| 1207 | |
| 1208 | The conversion is done by calling either \code{int()} or \code{long()} with |
| 1209 | the appropriate base (2, 8, 10, or 16). If this fails, so will \module{optparse}, |
| 1210 | although with a more useful error message. |
| 1211 | |
| 1212 | \code{float} and \code{complex} option arguments are converted directly with |
| 1213 | \code{float()} and \code{complex()}, with similar error-handling. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1214 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1215 | \code{choice} options are a subtype of \code{string} options. The \code{choices} |
| 1216 | option attribute (a sequence of strings) defines the set of allowed |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1217 | option arguments. \code{optparse.check{\_}choice()} compares |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1218 | user-supplied option arguments against this master list and raises |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1219 | OptionValueError if an invalid string is given. |
| 1220 | |
| 1221 | |
| 1222 | \subsubsection{Parsing arguments\label{optparse-parsing-arguments}} |
| 1223 | |
| 1224 | The whole point of creating and populating an OptionParser is to call |
| 1225 | its \method{parse{\_}args()} method: |
| 1226 | \begin{verbatim} |
Fred Drake | 2cb077a | 2007-05-17 19:29:43 +0000 | [diff] [blame] | 1227 | (options, args) = parser.parse_args(args=None, values=None) |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1228 | \end{verbatim} |
| 1229 | |
| 1230 | where the input parameters are |
| 1231 | \begin{description} |
| 1232 | \item[\code{args}] |
Greg Ward | d1c797e | 2006-06-11 14:42:41 +0000 | [diff] [blame] | 1233 | the list of arguments to process (default: \code{sys.argv{[}1:]}) |
Fred Drake | 2cb077a | 2007-05-17 19:29:43 +0000 | [diff] [blame] | 1234 | \item[\code{values}] |
Greg Ward | d1c797e | 2006-06-11 14:42:41 +0000 | [diff] [blame] | 1235 | object to store option arguments in (default: a new instance of |
| 1236 | optparse.Values) |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1237 | \end{description} |
| 1238 | |
| 1239 | and the return values are |
| 1240 | \begin{description} |
| 1241 | \item[\code{options}] |
Greg Ward | d1c797e | 2006-06-11 14:42:41 +0000 | [diff] [blame] | 1242 | the same object that was passed in as \code{options}, or the |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1243 | optparse.Values instance created by \module{optparse} |
| 1244 | \item[\code{args}] |
| 1245 | the leftover positional arguments after all options have been |
| 1246 | processed |
| 1247 | \end{description} |
| 1248 | |
| 1249 | The most common usage is to supply neither keyword argument. If you |
Greg Ward | d1c797e | 2006-06-11 14:42:41 +0000 | [diff] [blame] | 1250 | supply \code{options}, it will be modified with repeated \code{setattr()} |
| 1251 | calls (roughly one for every option argument stored to an option |
| 1252 | destination) and returned by \method{parse{\_}args()}. |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1253 | |
| 1254 | If \method{parse{\_}args()} encounters any errors in the argument list, it calls |
| 1255 | the OptionParser's \method{error()} method with an appropriate end-user error |
| 1256 | message. This ultimately terminates your process with an exit status of |
| 1257 | 2 (the traditional \UNIX{} exit status for command-line errors). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1258 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1259 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1260 | \subsubsection{Querying and manipulating your option parser\label{optparse-querying-manipulating-option-parser}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1261 | |
| 1262 | 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] | 1263 | there. OptionParser provides a couple of methods to help you out: |
| 1264 | \begin{description} |
| 1265 | \item[\code{has{\_}option(opt{\_}str)}] |
| 1266 | Return true if the OptionParser has an option with |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1267 | option string \code{opt{\_}str} (e.g., \programopt{-q} or \longprogramopt{verbose}). |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1268 | \item[\code{get{\_}option(opt{\_}str)}] |
| 1269 | Returns the Option instance with the option string \code{opt{\_}str}, or |
| 1270 | \code{None} if no options have that option string. |
| 1271 | \item[\code{remove{\_}option(opt{\_}str)}] |
| 1272 | If the OptionParser has an option corresponding to \code{opt{\_}str}, |
| 1273 | that option is removed. If that option provided any other |
| 1274 | option strings, all of those option strings become invalid. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1275 | If \code{opt{\_}str} does not occur in any option belonging to this |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1276 | OptionParser, raises ValueError. |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1277 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1278 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1279 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1280 | \subsubsection{Conflicts between options\label{optparse-conflicts-between-options}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1281 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1282 | If you're not careful, it's easy to define options with conflicting |
| 1283 | option strings: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1284 | \begin{verbatim} |
| 1285 | parser.add_option("-n", "--dry-run", ...) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1286 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1287 | parser.add_option("-n", "--noisy", ...) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1288 | \end{verbatim} |
| 1289 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1290 | (This is particularly true if you've defined your own OptionParser |
| 1291 | subclass with some standard options.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1292 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1293 | Every time you add an option, \module{optparse} checks for conflicts with existing |
| 1294 | options. If it finds any, it invokes the current conflict-handling |
| 1295 | mechanism. You can set the conflict-handling mechanism either in the |
| 1296 | constructor: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1297 | \begin{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1298 | parser = OptionParser(..., conflict_handler=handler) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1299 | \end{verbatim} |
| 1300 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1301 | or with a separate call: |
| 1302 | \begin{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1303 | parser.set_conflict_handler(handler) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1304 | \end{verbatim} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1305 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1306 | The available conflict handlers are: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1307 | \begin{quote} |
| 1308 | \begin{description} |
| 1309 | \item[\code{error} (default)] |
| 1310 | assume option conflicts are a programming error and raise |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1311 | OptionConflictError |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1312 | \item[\code{resolve}] |
| 1313 | resolve option conflicts intelligently (see below) |
| 1314 | \end{description} |
| 1315 | \end{quote} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1316 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1317 | As an example, let's define an OptionParser that resolves conflicts |
| 1318 | intelligently and add conflicting options to it: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1319 | \begin{verbatim} |
| 1320 | parser = OptionParser(conflict_handler="resolve") |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1321 | parser.add_option("-n", "--dry-run", ..., help="do no harm") |
| 1322 | parser.add_option("-n", "--noisy", ..., help="be noisy") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1323 | \end{verbatim} |
| 1324 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1325 | 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] | 1326 | using the \code{"-n"} option string. Since \code{conflict{\_}handler} is |
| 1327 | \code{"resolve"}, it resolves the situation by removing \code{"-n"} from the |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1328 | earlier option's list of option strings. Now \longprogramopt{dry-run} is the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1329 | only way for the user to activate that option. If the user asks for |
| 1330 | help, the help message will reflect that: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1331 | \begin{verbatim} |
| 1332 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1333 | --dry-run do no harm |
| 1334 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1335 | -n, --noisy be noisy |
| 1336 | \end{verbatim} |
| 1337 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1338 | It's possible to whittle away the option strings for a previously-added |
| 1339 | option until there are none left, and the user has no way of invoking |
| 1340 | that option from the command-line. In that case, \module{optparse} removes that |
| 1341 | option completely, so it doesn't show up in help text or anywhere else. |
| 1342 | Carrying on with our existing OptionParser: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1343 | \begin{verbatim} |
| 1344 | parser.add_option("--dry-run", ..., help="new dry-run option") |
| 1345 | \end{verbatim} |
| 1346 | |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1347 | At this point, the original \programopt{-n}/\longprogramopt{dry-run} option is no longer |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1348 | accessible, so \module{optparse} removes it, leaving this help text: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1349 | \begin{verbatim} |
| 1350 | options: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1351 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1352 | -n, --noisy be noisy |
| 1353 | --dry-run new dry-run option |
| 1354 | \end{verbatim} |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1355 | |
| 1356 | |
| 1357 | \subsubsection{Cleanup\label{optparse-cleanup}} |
| 1358 | |
| 1359 | OptionParser instances have several cyclic references. This should not |
| 1360 | be a problem for Python's garbage collector, but you may wish to break |
| 1361 | the cyclic references explicitly by calling \code{destroy()} on your |
| 1362 | OptionParser once you are done with it. This is particularly useful in |
| 1363 | long-running applications where large object graphs are reachable from |
| 1364 | your OptionParser. |
| 1365 | |
| 1366 | |
| 1367 | \subsubsection{Other methods\label{optparse-other-methods}} |
| 1368 | |
| 1369 | OptionParser supports several other public methods: |
| 1370 | \begin{itemize} |
| 1371 | \item {} |
| 1372 | \code{set{\_}usage(usage)} |
| 1373 | |
| 1374 | Set the usage string according to the rules described above for the |
| 1375 | \code{usage} constructor keyword argument. Passing \code{None} sets the |
| 1376 | default usage string; use \code{SUPPRESS{\_}USAGE} to suppress a usage |
| 1377 | message. |
| 1378 | |
| 1379 | \item {} |
| 1380 | \code{enable{\_}interspersed{\_}args()}, \code{disable{\_}interspersed{\_}args()} |
| 1381 | |
| 1382 | Enable/disable positional arguments interspersed with options, similar |
| 1383 | to GNU getopt (enabled by default). For example, if \code{"-a"} and |
| 1384 | \code{"-b"} are both simple options that take no arguments, \module{optparse} |
| 1385 | normally accepts this syntax: |
| 1386 | \begin{verbatim} |
| 1387 | prog -a arg1 -b arg2 |
| 1388 | \end{verbatim} |
| 1389 | |
| 1390 | and treats it as equivalent to |
| 1391 | \begin{verbatim} |
| 1392 | prog -a -b arg1 arg2 |
| 1393 | \end{verbatim} |
| 1394 | |
| 1395 | To disable this feature, call \code{disable{\_}interspersed{\_}args()}. This |
| 1396 | restores traditional \UNIX{} syntax, where option parsing stops with the |
| 1397 | first non-option argument. |
| 1398 | |
| 1399 | \item {} |
| 1400 | \code{set{\_}defaults(dest=value, ...)} |
| 1401 | |
| 1402 | Set default values for several option destinations at once. Using |
| 1403 | \method{set{\_}defaults()} is the preferred way to set default values for |
| 1404 | options, since multiple options can share the same destination. For |
| 1405 | example, if several ``mode'' options all set the same destination, any |
| 1406 | one of them can set the default, and the last one wins: |
| 1407 | \begin{verbatim} |
| 1408 | parser.add_option("--advanced", action="store_const", |
| 1409 | dest="mode", const="advanced", |
| 1410 | default="novice") # overridden below |
| 1411 | parser.add_option("--novice", action="store_const", |
| 1412 | dest="mode", const="novice", |
| 1413 | default="advanced") # overrides above setting |
| 1414 | \end{verbatim} |
| 1415 | |
| 1416 | To avoid this confusion, use \method{set{\_}defaults()}: |
| 1417 | \begin{verbatim} |
| 1418 | parser.set_defaults(mode="advanced") |
| 1419 | parser.add_option("--advanced", action="store_const", |
| 1420 | dest="mode", const="advanced") |
| 1421 | parser.add_option("--novice", action="store_const", |
| 1422 | dest="mode", const="novice") |
| 1423 | \end{verbatim} |
| 1424 | |
| 1425 | \end{itemize} |
Greg Ward | 48fae7a | 2006-07-23 16:05:51 +0000 | [diff] [blame] | 1426 | % $Id: reference.txt 519 2006-06-11 14:39:11Z gward $ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1427 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1428 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1429 | \subsection{Option Callbacks\label{optparse-option-callbacks}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1430 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1431 | When \module{optparse}'s built-in actions and types aren't quite enough for your |
| 1432 | needs, you have two choices: extend \module{optparse} or define a callback option. |
| 1433 | Extending \module{optparse} is more general, but overkill for a lot of simple |
| 1434 | cases. Quite often a simple callback is all you need. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1435 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1436 | There are two steps to defining a callback option: |
| 1437 | \begin{itemize} |
| 1438 | \item {} |
| 1439 | define the option itself using the \code{callback} action |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1440 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1441 | \item {} |
| 1442 | write the callback; this is a function (or method) that |
| 1443 | takes at least four arguments, as described below |
| 1444 | |
| 1445 | \end{itemize} |
| 1446 | |
| 1447 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1448 | \subsubsection{Defining a callback option\label{optparse-defining-callback-option}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1449 | |
| 1450 | As always, the easiest way to define a callback option is by using the |
| 1451 | \code{parser.add{\_}option()} method. Apart from \member{action}, the only option |
| 1452 | attribute you must specify is \code{callback}, the function to call: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1453 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1454 | parser.add_option("-c", action="callback", callback=my_callback) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1455 | \end{verbatim} |
| 1456 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1457 | \code{callback} is a function (or other callable object), so you must have |
| 1458 | already defined \code{my{\_}callback()} when you create this callback option. |
| 1459 | In this simple case, \module{optparse} doesn't even know if \programopt{-c} takes any |
| 1460 | arguments, which usually means that the option takes no arguments{---}the |
| 1461 | mere presence of \programopt{-c} on the command-line is all it needs to know. In |
| 1462 | some circumstances, though, you might want your callback to consume an |
| 1463 | arbitrary number of command-line arguments. This is where writing |
| 1464 | callbacks gets tricky; it's covered later in this section. |
| 1465 | |
| 1466 | \module{optparse} always passes four particular arguments to your callback, and it |
| 1467 | will only pass additional arguments if you specify them via |
| 1468 | \code{callback{\_}args} and \code{callback{\_}kwargs}. Thus, the minimal callback |
| 1469 | function signature is: |
| 1470 | \begin{verbatim} |
| 1471 | def my_callback(option, opt, value, parser): |
| 1472 | \end{verbatim} |
| 1473 | |
| 1474 | The four arguments to a callback are described below. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1475 | |
| 1476 | There are several other option attributes that you can supply when you |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1477 | define a callback option: |
| 1478 | \begin{description} |
| 1479 | \item[\member{type}] |
| 1480 | has its usual meaning: as with the \code{store} or \code{append} actions, |
| 1481 | it instructs \module{optparse} to consume one argument and convert it to |
| 1482 | \member{type}. Rather than storing the converted value(s) anywhere, |
| 1483 | though, \module{optparse} passes it to your callback function. |
| 1484 | \item[\code{nargs}] |
| 1485 | also has its usual meaning: if it is supplied and {\textgreater} 1, \module{optparse} will |
| 1486 | consume \code{nargs} arguments, each of which must be convertible to |
| 1487 | \member{type}. It then passes a tuple of converted values to your |
| 1488 | callback. |
| 1489 | \item[\code{callback{\_}args}] |
| 1490 | a tuple of extra positional arguments to pass to the callback |
| 1491 | \item[\code{callback{\_}kwargs}] |
| 1492 | a dictionary of extra keyword arguments to pass to the callback |
| 1493 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1494 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1495 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1496 | \subsubsection{How callbacks are called\label{optparse-how-callbacks-called}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1497 | |
| 1498 | All callbacks are called as follows: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1499 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1500 | func(option, opt_str, value, parser, *args, **kwargs) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1501 | \end{verbatim} |
| 1502 | |
| 1503 | where |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1504 | \begin{description} |
| 1505 | \item[\code{option}] |
| 1506 | is the Option instance that's calling the callback |
| 1507 | \item[\code{opt{\_}str}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1508 | 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] | 1509 | callback. (If an abbreviated long option was used, \code{opt{\_}str} will |
| 1510 | be the full, canonical option string{---}e.g. if the user puts |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1511 | \longprogramopt{foo} on the command-line as an abbreviation for |
| 1512 | \longprogramopt{foobar}, then \code{opt{\_}str} will be \longprogramopt{foobar}.) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1513 | \item[\code{value}] |
| 1514 | is the argument to this option seen on the command-line. \module{optparse} will |
| 1515 | only expect an argument if \member{type} is set; the type of \code{value} |
| 1516 | will be the type implied by the option's type. If \member{type} for this |
| 1517 | option is \code{None} (no argument expected), then \code{value} will be |
| 1518 | \code{None}. If \code{nargs} {\textgreater} 1, \code{value} will be a tuple of values of |
| 1519 | the appropriate type. |
| 1520 | \item[\code{parser}] |
| 1521 | is the OptionParser instance driving the whole thing, mainly |
| 1522 | useful because you can access some other interesting data through |
| 1523 | its instance attributes: |
| 1524 | \begin{description} |
| 1525 | \item[\code{parser.largs}] |
| 1526 | the current list of leftover arguments, ie. arguments that have |
| 1527 | been consumed but are neither options nor option arguments. |
| 1528 | Feel free to modify \code{parser.largs}, e.g. by adding more |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1529 | arguments to it. (This list will become \code{args}, the second |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1530 | return value of \method{parse{\_}args()}.) |
| 1531 | \item[\code{parser.rargs}] |
| 1532 | the current list of remaining arguments, ie. with \code{opt{\_}str} and |
| 1533 | \code{value} (if applicable) removed, and only the arguments |
| 1534 | following them still there. Feel free to modify |
| 1535 | \code{parser.rargs}, e.g. by consuming more arguments. |
| 1536 | \item[\code{parser.values}] |
| 1537 | the object where option values are by default stored (an |
| 1538 | instance of optparse.OptionValues). This lets callbacks use the |
| 1539 | same mechanism as the rest of \module{optparse} for storing option values; |
| 1540 | you don't need to mess around with globals or closures. You can |
| 1541 | also access or modify the value(s) of any options already |
| 1542 | encountered on the command-line. |
| 1543 | \end{description} |
Raymond Hettinger | 79e0531 | 2004-12-31 01:07:27 +0000 | [diff] [blame] | 1544 | \item[\code{args}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1545 | is a tuple of arbitrary positional arguments supplied via the |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1546 | \code{callback{\_}args} option attribute. |
| 1547 | \item[\code{kwargs}] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1548 | is a dictionary of arbitrary keyword arguments supplied via |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1549 | \code{callback{\_}kwargs}. |
| 1550 | \end{description} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1551 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1552 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1553 | \subsubsection{Raising errors in a callback\label{optparse-raising-errors-in-callback}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1554 | |
Greg Ward | ab05edc | 2006-04-23 03:47:58 +0000 | [diff] [blame] | 1555 | The callback function should raise OptionValueError if there are any |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1556 | problems with the option or its argument(s). \module{optparse} catches this and |
| 1557 | terminates the program, printing the error message you supply to |
| 1558 | stderr. Your message should be clear, concise, accurate, and mention |
| 1559 | the option at fault. Otherwise, the user will have a hard time |
| 1560 | figuring out what he did wrong. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1561 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1562 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1563 | \subsubsection{Callback example 1: trivial callback\label{optparse-callback-example-1}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1564 | |
| 1565 | Here's an example of a callback option that takes no arguments, and |
| 1566 | simply records that the option was seen: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1567 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1568 | def record_foo_seen(option, opt_str, value, parser): |
| 1569 | parser.saw_foo = True |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1570 | |
| 1571 | parser.add_option("--foo", action="callback", callback=record_foo_seen) |
| 1572 | \end{verbatim} |
| 1573 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1574 | Of course, you could do that with the \code{store{\_}true} action. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1575 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1576 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1577 | \subsubsection{Callback example 2: check option order\label{optparse-callback-example-2}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1578 | |
| 1579 | Here's a slightly more interesting example: record the fact that |
| 1580 | \code{"-a"} is seen, but blow up if it comes after \code{"-b"} in the |
| 1581 | command-line. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1582 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1583 | def check_order(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1584 | if parser.values.b: |
| 1585 | raise OptionValueError("can't use -a after -b") |
| 1586 | parser.values.a = 1 |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1587 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1588 | parser.add_option("-a", action="callback", callback=check_order) |
| 1589 | parser.add_option("-b", action="store_true", dest="b") |
| 1590 | \end{verbatim} |
| 1591 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1592 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1593 | \subsubsection{Callback example 3: check option order (generalized)\label{optparse-callback-example-3}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1594 | |
| 1595 | If you want to re-use this callback for several similar options (set a |
| 1596 | flag, but blow up if \code{"-b"} has already been seen), it needs a bit of |
| 1597 | work: the error message and the flag that it sets must be |
| 1598 | generalized. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1599 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1600 | def check_order(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1601 | if parser.values.b: |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1602 | raise OptionValueError("can't use %s after -b" % opt_str) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1603 | setattr(parser.values, option.dest, 1) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1604 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1605 | parser.add_option("-a", action="callback", callback=check_order, dest='a') |
| 1606 | parser.add_option("-b", action="store_true", dest="b") |
| 1607 | parser.add_option("-c", action="callback", callback=check_order, dest='c') |
| 1608 | \end{verbatim} |
| 1609 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1610 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1611 | \subsubsection{Callback example 4: check arbitrary condition\label{optparse-callback-example-4}} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1612 | |
| 1613 | 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] | 1614 | to checking the values of already-defined options. For example, if |
| 1615 | you have options that should not be called when the moon is full, all |
| 1616 | you have to do is this: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1617 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1618 | def check_moon(option, opt_str, value, parser): |
| 1619 | if is_moon_full(): |
| 1620 | raise OptionValueError("%s option invalid when moon is full" |
| 1621 | % opt_str) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1622 | setattr(parser.values, option.dest, 1) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1623 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1624 | parser.add_option("--foo", |
| 1625 | action="callback", callback=check_moon, dest="foo") |
| 1626 | \end{verbatim} |
| 1627 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1628 | (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] | 1629 | reader.) |
| 1630 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1631 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1632 | \subsubsection{Callback example 5: fixed arguments\label{optparse-callback-example-5}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1633 | |
| 1634 | Things get slightly more interesting when you define callback options |
| 1635 | that take a fixed number of arguments. Specifying that a callback |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1636 | option takes arguments is similar to defining a \code{store} or \code{append} |
| 1637 | option: if you define \member{type}, then the option takes one argument that |
| 1638 | must be convertible to that type; if you further define \code{nargs}, then |
| 1639 | the option takes \code{nargs} arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1640 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1641 | Here's an example that just emulates the standard \code{store} action: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1642 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1643 | def store_value(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1644 | setattr(parser.values, option.dest, value) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1645 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1646 | parser.add_option("--foo", |
| 1647 | action="callback", callback=store_value, |
| 1648 | type="int", nargs=3, dest="foo") |
| 1649 | \end{verbatim} |
| 1650 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1651 | Note that \module{optparse} takes care of consuming 3 arguments and converting them |
| 1652 | to integers for you; all you have to do is store them. (Or whatever; |
| 1653 | obviously you don't need a callback for this example.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1654 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1655 | |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1656 | \subsubsection{Callback example 6: variable arguments\label{optparse-callback-example-6}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1657 | |
| 1658 | 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] | 1659 | arguments. For this case, you must write a callback, as \module{optparse} doesn't |
| 1660 | provide any built-in capabilities for it. And you have to deal with |
| 1661 | certain intricacies of conventional \UNIX{} command-line parsing that \module{optparse} |
| 1662 | normally handles for you. In particular, callbacks should implement |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1663 | the conventional rules for bare \longprogramopt{} and \programopt{-} arguments: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1664 | \begin{itemize} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1665 | \item {} |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1666 | either \longprogramopt{} or \programopt{-} can be option arguments |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1667 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1668 | \item {} |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1669 | bare \longprogramopt{} (if not the argument to some option): halt command-line |
| 1670 | processing and discard the \longprogramopt{} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1671 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1672 | \item {} |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1673 | bare \programopt{-} (if not the argument to some option): halt command-line |
| 1674 | processing but keep the \programopt{-} (append it to \code{parser.largs}) |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1675 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1676 | \end{itemize} |
| 1677 | |
| 1678 | If you want an option that takes a variable number of arguments, there |
| 1679 | are several subtle, tricky issues to worry about. The exact |
| 1680 | implementation you choose will be based on which trade-offs you're |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1681 | willing to make for your application (which is why \module{optparse} doesn't support |
| 1682 | this sort of thing directly). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1683 | |
| 1684 | Nevertheless, here's a stab at a callback for an option with variable |
| 1685 | arguments: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1686 | \begin{verbatim} |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1687 | def vararg_callback(option, opt_str, value, parser): |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1688 | assert value is None |
| 1689 | done = 0 |
| 1690 | value = [] |
| 1691 | rargs = parser.rargs |
| 1692 | while rargs: |
| 1693 | arg = rargs[0] |
| 1694 | |
| 1695 | # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f", |
| 1696 | # etc. Note that this also stops on "-3" or "-3.0", so if |
| 1697 | # your option takes numeric values, you will need to handle |
| 1698 | # this. |
| 1699 | if ((arg[:2] == "--" and len(arg) > 2) or |
| 1700 | (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): |
| 1701 | break |
| 1702 | else: |
| 1703 | value.append(arg) |
| 1704 | del rargs[0] |
| 1705 | |
| 1706 | setattr(parser.values, option.dest, value) |
| 1707 | |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1708 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1709 | parser.add_option("-c", "--callback", |
| 1710 | action="callback", callback=varargs) |
| 1711 | \end{verbatim} |
| 1712 | |
| 1713 | The main weakness with this particular implementation is that negative |
Greg Ward | b6f7fb7 | 2004-09-28 01:30:23 +0000 | [diff] [blame] | 1714 | numbers in the arguments following \code{"-c"} will be interpreted as |
| 1715 | further options (probably causing an error), rather than as arguments to |
| 1716 | \code{"-c"}. Fixing this is left as an exercise for the reader. |
Greg Ward | e644a1b | 2004-10-01 01:16:39 +0000 | [diff] [blame] | 1717 | % $Id: callbacks.txt 415 2004-09-30 02:26:17Z greg $ |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1718 | |
Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 1719 | |
| 1720 | \subsection{Extending \module{optparse}\label{optparse-extending-optparse}} |
| 1721 | |
| 1722 | Since the two major controlling factors in how \module{optparse} interprets |
| 1723 | command-line options are the action and type of each option, the most |
| 1724 | likely direction of extension is to add new actions and new types. |
| 1725 | |
| 1726 | |
| 1727 | \subsubsection{Adding new types\label{optparse-adding-new-types}} |
| 1728 | |
| 1729 | To add new types, you need to define your own subclass of \module{optparse}'s Option |
| 1730 | class. This class has a couple of attributes that define \module{optparse}'s types: |
| 1731 | \member{TYPES} and \member{TYPE{\_}CHECKER}. |
| 1732 | |
| 1733 | \member{TYPES} is a tuple of type names; in your subclass, simply define a new |
| 1734 | tuple \member{TYPES} that builds on the standard one. |
| 1735 | |
| 1736 | \member{TYPE{\_}CHECKER} is a dictionary mapping type names to type-checking |
| 1737 | functions. A type-checking function has the following signature: |
| 1738 | \begin{verbatim} |
| 1739 | def check_mytype(option, opt, value) |
| 1740 | \end{verbatim} |
| 1741 | |
| 1742 | where \code{option} is an \class{Option} instance, \code{opt} is an option string |
| 1743 | (e.g., \code{"-f"}), and \code{value} is the string from the command line that |
| 1744 | must be checked and converted to your desired type. \code{check{\_}mytype()} |
| 1745 | should return an object of the hypothetical type \code{mytype}. The value |
| 1746 | returned by a type-checking function will wind up in the OptionValues |
| 1747 | instance returned by \method{OptionParser.parse{\_}args()}, or be passed to a |
| 1748 | callback as the \code{value} parameter. |
| 1749 | |
| 1750 | Your type-checking function should raise OptionValueError if it |
| 1751 | encounters any problems. OptionValueError takes a single string |
| 1752 | argument, which is passed as-is to OptionParser's \method{error()} method, |
| 1753 | which in turn prepends the program name and the string \code{"error:"} and |
| 1754 | prints everything to stderr before terminating the process. |
| 1755 | |
| 1756 | Here's a silly example that demonstrates adding a \code{complex} option |
| 1757 | type to parse Python-style complex numbers on the command line. (This |
| 1758 | is even sillier than it used to be, because \module{optparse} 1.3 added built-in |
| 1759 | support for complex numbers, but never mind.) |
| 1760 | |
| 1761 | First, the necessary imports: |
| 1762 | \begin{verbatim} |
| 1763 | from copy import copy |
| 1764 | from optparse import Option, OptionValueError |
| 1765 | \end{verbatim} |
| 1766 | |
| 1767 | You need to define your type-checker first, since it's referred to later |
| 1768 | (in the \member{TYPE{\_}CHECKER} class attribute of your Option subclass): |
| 1769 | \begin{verbatim} |
| 1770 | def check_complex(option, opt, value): |
| 1771 | try: |
| 1772 | return complex(value) |
| 1773 | except ValueError: |
| 1774 | raise OptionValueError( |
| 1775 | "option %s: invalid complex value: %r" % (opt, value)) |
| 1776 | \end{verbatim} |
| 1777 | |
| 1778 | Finally, the Option subclass: |
| 1779 | \begin{verbatim} |
| 1780 | class MyOption (Option): |
| 1781 | TYPES = Option.TYPES + ("complex",) |
| 1782 | TYPE_CHECKER = copy(Option.TYPE_CHECKER) |
| 1783 | TYPE_CHECKER["complex"] = check_complex |
| 1784 | \end{verbatim} |
| 1785 | |
| 1786 | (If we didn't make a \function{copy()} of \member{Option.TYPE{\_}CHECKER}, we would end |
| 1787 | up modifying the \member{TYPE{\_}CHECKER} attribute of \module{optparse}'s Option class. |
| 1788 | This being Python, nothing stops you from doing that except good manners |
| 1789 | and common sense.) |
| 1790 | |
| 1791 | That's it! Now you can write a script that uses the new option type |
| 1792 | just like any other \module{optparse}-based script, except you have to instruct your |
| 1793 | OptionParser to use MyOption instead of Option: |
| 1794 | \begin{verbatim} |
| 1795 | parser = OptionParser(option_class=MyOption) |
| 1796 | parser.add_option("-c", type="complex") |
| 1797 | \end{verbatim} |
| 1798 | |
| 1799 | Alternately, you can build your own option list and pass it to |
| 1800 | OptionParser; if you don't use \method{add{\_}option()} in the above way, you |
| 1801 | don't need to tell OptionParser which option class to use: |
| 1802 | \begin{verbatim} |
| 1803 | option_list = [MyOption("-c", action="store", type="complex", dest="c")] |
| 1804 | parser = OptionParser(option_list=option_list) |
| 1805 | \end{verbatim} |
| 1806 | |
| 1807 | |
| 1808 | \subsubsection{Adding new actions\label{optparse-adding-new-actions}} |
| 1809 | |
| 1810 | Adding new actions is a bit trickier, because you have to understand |
| 1811 | that \module{optparse} has a couple of classifications for actions: |
| 1812 | \begin{description} |
| 1813 | \item[``store'' actions] |
| 1814 | actions that result in \module{optparse} storing a value to an attribute of the |
| 1815 | current OptionValues instance; these options require a \member{dest} |
| 1816 | attribute to be supplied to the Option constructor |
| 1817 | \item[``typed'' actions] |
| 1818 | actions that take a value from the command line and expect it to be |
| 1819 | of a certain type; or rather, a string that can be converted to a |
| 1820 | certain type. These options require a \member{type} attribute to the |
| 1821 | Option constructor. |
| 1822 | \end{description} |
| 1823 | |
| 1824 | These are overlapping sets: some default ``store'' actions are \code{store}, |
| 1825 | \code{store{\_}const}, \code{append}, and \code{count}, while the default ``typed'' |
| 1826 | actions are \code{store}, \code{append}, and \code{callback}. |
| 1827 | |
| 1828 | When you add an action, you need to categorize it by listing it in at |
| 1829 | least one of the following class attributes of Option (all are lists of |
| 1830 | strings): |
| 1831 | \begin{description} |
| 1832 | \item[\member{ACTIONS}] |
| 1833 | all actions must be listed in ACTIONS |
| 1834 | \item[\member{STORE{\_}ACTIONS}] |
| 1835 | ``store'' actions are additionally listed here |
| 1836 | \item[\member{TYPED{\_}ACTIONS}] |
| 1837 | ``typed'' actions are additionally listed here |
| 1838 | \item[\code{ALWAYS{\_}TYPED{\_}ACTIONS}] |
| 1839 | actions that always take a type (i.e. whose options always take a |
| 1840 | value) are additionally listed here. The only effect of this is |
| 1841 | that \module{optparse} assigns the default type, \code{string}, to options with no |
| 1842 | explicit type whose action is listed in \code{ALWAYS{\_}TYPED{\_}ACTIONS}. |
| 1843 | \end{description} |
| 1844 | |
| 1845 | In order to actually implement your new action, you must override |
| 1846 | Option's \method{take{\_}action()} method and add a case that recognizes your |
| 1847 | action. |
| 1848 | |
| 1849 | For example, let's add an \code{extend} action. This is similar to the |
| 1850 | standard \code{append} action, but instead of taking a single value from |
| 1851 | the command-line and appending it to an existing list, \code{extend} will |
| 1852 | take multiple values in a single comma-delimited string, and extend an |
Georg Brandl | cdceeb8 | 2007-09-24 17:56:12 +0000 | [diff] [blame] | 1853 | existing list with them. That is, if \longprogramopt{names} is an \code{extend} |
Greg Ward | c5221e1 | 2006-06-10 16:40:01 +0000 | [diff] [blame] | 1854 | option of type \code{string}, the command line |
| 1855 | \begin{verbatim} |
| 1856 | --names=foo,bar --names blah --names ding,dong |
| 1857 | \end{verbatim} |
| 1858 | |
| 1859 | would result in a list |
| 1860 | \begin{verbatim} |
| 1861 | ["foo", "bar", "blah", "ding", "dong"] |
| 1862 | \end{verbatim} |
| 1863 | |
| 1864 | Again we define a subclass of Option: |
| 1865 | \begin{verbatim} |
| 1866 | class MyOption (Option): |
| 1867 | |
| 1868 | ACTIONS = Option.ACTIONS + ("extend",) |
| 1869 | STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) |
| 1870 | TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) |
| 1871 | ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",) |
| 1872 | |
| 1873 | def take_action(self, action, dest, opt, value, values, parser): |
| 1874 | if action == "extend": |
| 1875 | lvalue = value.split(",") |
| 1876 | values.ensure_value(dest, []).extend(lvalue) |
| 1877 | else: |
| 1878 | Option.take_action( |
| 1879 | self, action, dest, opt, value, values, parser) |
| 1880 | \end{verbatim} |
| 1881 | |
| 1882 | Features of note: |
| 1883 | \begin{itemize} |
| 1884 | \item {} |
| 1885 | \code{extend} both expects a value on the command-line and stores that |
| 1886 | value somewhere, so it goes in both \member{STORE{\_}ACTIONS} and |
| 1887 | \member{TYPED{\_}ACTIONS} |
| 1888 | |
| 1889 | \item {} |
| 1890 | to ensure that \module{optparse} assigns the default type of \code{string} to |
| 1891 | \code{extend} actions, we put the \code{extend} action in |
| 1892 | \code{ALWAYS{\_}TYPED{\_}ACTIONS} as well |
| 1893 | |
| 1894 | \item {} |
| 1895 | \method{MyOption.take{\_}action()} implements just this one new action, and |
| 1896 | passes control back to \method{Option.take{\_}action()} for the standard |
| 1897 | \module{optparse} actions |
| 1898 | |
| 1899 | \item {} |
| 1900 | \code{values} is an instance of the optparse{\_}parser.Values class, |
| 1901 | which provides the very useful \method{ensure{\_}value()} method. |
| 1902 | \method{ensure{\_}value()} is essentially \function{getattr()} with a safety valve; |
| 1903 | it is called as |
| 1904 | \begin{verbatim} |
| 1905 | values.ensure_value(attr, value) |
| 1906 | \end{verbatim} |
| 1907 | |
| 1908 | If the \code{attr} attribute of \code{values} doesn't exist or is None, then |
| 1909 | ensure{\_}value() first sets it to \code{value}, and then returns 'value. |
| 1910 | This is very handy for actions like \code{extend}, \code{append}, and |
| 1911 | \code{count}, all of which accumulate data in a variable and expect that |
| 1912 | variable to be of a certain type (a list for the first two, an integer |
| 1913 | for the latter). Using \method{ensure{\_}value()} means that scripts using |
| 1914 | your action don't have to worry about setting a default value for the |
| 1915 | option destinations in question; they can just leave the default as |
| 1916 | None and \method{ensure{\_}value()} will take care of getting it right when |
| 1917 | it's needed. |
| 1918 | |
| 1919 | \end{itemize} |
| 1920 | % $Id: extending.txt 517 2006-06-10 16:18:11Z gward $ |
| 1921 | |