Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1 | \section{\module{optparse} --- |
| 2 | Powerful parser for command line options.} |
| 3 | |
| 4 | \declaremodule{standard}{optparse} |
| 5 | \moduleauthor{Greg Ward}{gward@python.net} |
| 6 | \sectionauthor{Johannes Gijsbers}{jlgijsbers@users.sf.net} |
| 7 | \sectionauthor{Greg Ward}{gward@python.net} |
| 8 | |
| 9 | \modulesynopsis{Powerful, flexible, extensible, easy-to-use command-line |
| 10 | parsing library.} |
| 11 | |
| 12 | \versionadded{2.3} |
| 13 | |
| 14 | The \module{optparse} module is a powerful, flexible, extensible, |
| 15 | easy-to-use command-line parsing library for Python. Using |
| 16 | \module{optparse}, you can add intelligent, sophisticated handling of |
| 17 | command-line options to your scripts with very little overhead. |
| 18 | |
| 19 | Here's an example of using \module{optparse} to add some command-line |
| 20 | options to a simple script: |
| 21 | |
| 22 | \begin{verbatim} |
| 23 | from optparse import OptionParser |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 24 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 25 | parser = OptionParser() |
| 26 | parser.add_option("-f", "--file", dest="filename", |
| 27 | help="write report to FILE", metavar="FILE") |
| 28 | parser.add_option("-q", "--quiet", |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 29 | action="store_false", dest="verbose", default=True, |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 30 | help="don't print status messages to stdout") |
| 31 | |
| 32 | (options, args) = parser.parse_args() |
| 33 | \end{verbatim} |
| 34 | |
| 35 | With these few lines of code, users of your script can now do the |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 36 | ``usual thing'' on the command-line: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 37 | |
| 38 | \begin{verbatim} |
| 39 | $ <yourscript> -f outfile --quiet |
| 40 | $ <yourscript> -qfoutfile |
| 41 | $ <yourscript> --file=outfile -q |
| 42 | $ <yourscript> --quiet --file outfile |
| 43 | \end{verbatim} |
| 44 | |
| 45 | (All of these result in \code{options.filename == "outfile"} and |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 46 | \code{options.verbose == False}, just as you might expect.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 47 | |
| 48 | Even niftier, users can run one of |
| 49 | \begin{verbatim} |
| 50 | $ <yourscript> -h |
| 51 | $ <yourscript> --help |
| 52 | \end{verbatim} |
| 53 | and \module{optparse} will print out a brief summary of your script's |
| 54 | options: |
| 55 | |
| 56 | \begin{verbatim} |
| 57 | usage: <yourscript> [options] |
| 58 | |
| 59 | options: |
| 60 | -h, --help show this help message and exit |
| 61 | -fFILE, --file=FILE write report to FILE |
| 62 | -q, --quiet don't print status messages to stdout |
| 63 | \end{verbatim} |
| 64 | |
| 65 | That's just a taste of the flexibility \module{optparse} gives you in |
| 66 | parsing your command-line. |
| 67 | |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 68 | \subsection{Philosophy\label{optparse-philosophy}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 69 | |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 70 | The purpose of \module{optparse} is to make it very easy to provide the |
| 71 | most standard, obvious, straightforward, and user-friendly user |
| 72 | interface for \UNIX{} command-line programs. The \module{optparse} |
| 73 | philosophy is heavily influenced by the \UNIX{} and GNU toolkits, and |
| 74 | this section is meant to explain that philosophy. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 75 | |
| 76 | \subsubsection{Terminology\label{optparse-terminology}} |
| 77 | |
| 78 | First, we need to establish some terminology. |
| 79 | |
| 80 | \begin{definitions} |
| 81 | \term{argument} |
| 82 | a chunk of text that a user enters on the command-line, and that the |
| 83 | shell passes to \cfunction{execl()} or \cfunction{execv()}. In |
| 84 | Python, arguments are elements of |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 85 | \code{sys.argv[1:]}. (\code{sys.argv[0]} is the name of the program |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 86 | being executed; in the context of parsing arguments, it's not very |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 87 | important.) \UNIX{} shells also use the term ``word''. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 88 | |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 89 | It is occasionally desirable to use an argument list other than |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 90 | \code{sys.argv[1:]}, so you should read ``argument'' as ``an element of |
| 91 | \code{sys.argv[1:]}, or of some other list provided as a substitute for |
| 92 | \code{sys.argv[1:]}''. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 93 | |
| 94 | \term{option} |
| 95 | an argument used to supply extra information to guide or customize |
| 96 | the execution of a program. There are many different syntaxes for |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 97 | options; the traditional \UNIX{} syntax is \programopt{-} followed by a |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 98 | single letter, e.g. \programopt{-x} or \programopt{-F}. Also, |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 99 | traditional \UNIX{} syntax allows multiple options to be merged into a |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 100 | single argument, e.g. \programopt{-x -F} is equivalent to |
| 101 | \programopt{-xF}. The GNU project introduced \longprogramopt{} |
| 102 | followed by a series of hyphen-separated words, |
| 103 | e.g. \longprogramopt{file} or \longprogramopt{dry-run}. These are |
| 104 | the only two option syntaxes provided by \module{optparse}. |
| 105 | |
| 106 | Some other option syntaxes that the world has seen include: |
| 107 | |
| 108 | \begin{itemize} |
| 109 | \item a hyphen followed by a few letters, e.g. \programopt{-pf} (this is |
Greg Ward | b4e3319 | 2003-05-03 19:16:36 +0000 | [diff] [blame] | 110 | \emph{not} the same as multiple options merged into a single |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 111 | argument.) |
| 112 | \item a hyphen followed by a whole word, e.g. \programopt{-file} (this is |
| 113 | technically equivalent to the previous syntax, but they aren't |
| 114 | usually seen in the same program.) |
| 115 | \item a plus sign followed by a single letter, or a few letters, |
| 116 | or a word, e.g. \programopt{+f}, \programopt{+rgb}. |
| 117 | \item a slash followed by a letter, or a few letters, or a word, e.g. |
| 118 | \programopt{/f}, \programopt{/file}. |
| 119 | \end{itemize} |
| 120 | |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 121 | \module{optparse} does not support these option syntaxes, and it never |
| 122 | will. (If you really want to use one of those option syntaxes, you'll |
| 123 | have to subclass \class{OptionParser} and override all the difficult |
| 124 | bits. But please don't! \module{optparse} does things the traditional |
| 125 | \UNIX/GNU way deliberately; the first three are non-standard anywhere, |
| 126 | and the last one makes sense only if you're exclusively targeting |
| 127 | MS-DOS/Windows and/or VMS.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 128 | |
| 129 | \term{option argument} |
| 130 | an argument that follows an option, is closely associated with that |
| 131 | option, and is consumed from the argument list when the option is. |
| 132 | Often, option arguments may also be included in the same argument as |
| 133 | the option, e.g. : |
| 134 | |
| 135 | \begin{verbatim} |
| 136 | ["-f", "foo"] |
| 137 | \end{verbatim} |
| 138 | |
| 139 | may be equivalent to: |
| 140 | |
| 141 | \begin{verbatim} |
| 142 | ["-ffoo"] |
| 143 | \end{verbatim} |
| 144 | |
| 145 | (\module{optparse} supports this syntax.) |
| 146 | |
| 147 | Some options never take an argument. Some options always take an |
| 148 | argument. Lots of people want an ``optional option arguments'' feature, |
| 149 | meaning that some options will take an argument if they see it, and |
| 150 | won't if they don't. This is somewhat controversial, because it makes |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 151 | parsing ambiguous: if \programopt{-a} and \programopt{-b} are both |
| 152 | options, and \programopt{-a} takes an optional argument, how do we |
| 153 | interpret \programopt{-ab}? \module{optparse} does not support optional |
| 154 | option arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 155 | |
| 156 | \term{positional argument} |
| 157 | something leftover in the argument list after options have been |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 158 | parsed, i.e., after options and their arguments have been parsed and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 159 | removed from the argument list. |
| 160 | |
| 161 | \term{required option} |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 162 | an option that must be supplied on the command-line. The phrase |
| 163 | ``required option'' is an oxymoron; the presence of ``required options'' |
| 164 | in a program is usually a sign of careless user interface design. |
| 165 | \module{optparse} doesn't prevent you from implementing required |
| 166 | options, but doesn't give you much help with it either. See ``Extending |
| 167 | Examples'' (section~\ref{optparse-extending-examples}) for two ways to |
| 168 | implement required options with \module{optparse}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 169 | |
| 170 | \end{definitions} |
| 171 | |
| 172 | For example, consider this hypothetical command-line: |
| 173 | |
| 174 | \begin{verbatim} |
| 175 | prog -v --report /tmp/report.txt foo bar |
| 176 | \end{verbatim} |
| 177 | |
| 178 | \programopt{-v} and \longprogramopt{report} are both options. Assuming |
| 179 | the \longprogramopt{report} option takes one argument, |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 180 | \code{/tmp/report.txt} is an option argument. \code{foo} and \code{bar} |
| 181 | are positional arguments. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 182 | |
| 183 | \subsubsection{What are options for?\label{optparse-options}} |
| 184 | |
| 185 | Options are used to provide extra information to tune or customize the |
Greg Ward | 649625b | 2003-05-03 20:41:37 +0000 | [diff] [blame] | 186 | execution of a program. In case it wasn't clear, options should be |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 187 | \emph{optional}. A program should be able to run just fine with no |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 188 | options whatsoever. (Pick a random program from the \UNIX{} or GNU |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 189 | toolsets. Can it run without any options at all and still make sense? |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 190 | The only exceptions I can think of are \program{find}, \program{tar}, |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 191 | and \program{dd}---all of which are mutant oddballs that have been |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 192 | rightly criticized for their non-standard syntax and confusing |
| 193 | interfaces.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 194 | |
| 195 | Lots of people want their programs to have ``required options''. |
| 196 | Think about it. If it's required, then it's \emph{not optional}! If |
| 197 | there is a piece of information that your program absolutely requires |
| 198 | in order to run successfully, that's what positional arguments are |
| 199 | for. (However, if you insist on adding ``required options'' to your |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 200 | programs, look in ``Extending Examples'' |
| 201 | (section~\ref{optparse-extending-examples}) for two ways of |
| 202 | implementing them with \module{optparse}.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 203 | |
| 204 | Consider the humble \program{cp} utility, for copying files. It |
| 205 | doesn't make much sense to try to copy files without supplying a |
| 206 | destination and at least one source. Hence, \program{cp} fails if you |
| 207 | run it with no arguments. However, it has a flexible, useful syntax |
| 208 | that does not rely on options at all: |
| 209 | |
| 210 | \begin{verbatim} |
| 211 | $ cp SOURCE DEST |
| 212 | $ cp SOURCE ... DEST-DIR |
| 213 | \end{verbatim} |
| 214 | |
| 215 | You can get pretty far with just that. Most \program{cp} |
| 216 | implementations provide a bunch of options to tweak exactly how the |
| 217 | files are copied: you can preserve mode and modification time, avoid |
| 218 | following symlinks, ask before clobbering existing files, etc. But |
| 219 | none of this distracts from the core mission of \program{cp}, which is |
| 220 | to copy one file to another, or N files to another directory. |
| 221 | |
| 222 | \subsubsection{What are positional arguments for? \label{optparse-positional-arguments}} |
| 223 | |
| 224 | In case it wasn't clear from the above example: positional arguments |
| 225 | are for those pieces of information that your program absolutely, |
| 226 | positively requires to run. |
| 227 | |
| 228 | A good user interface should have as few absolute requirements as |
| 229 | possible. If your program requires 17 distinct pieces of information in |
| 230 | order to run successfully, it doesn't much matter \emph{how} you get that |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 231 | information from the user---most people will give up and walk away |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 232 | before they successfully run the program. This applies whether the user |
| 233 | interface is a command-line, a configuration file, a GUI, or whatever: |
| 234 | if you make that many demands on your users, most of them will just give |
| 235 | up. |
| 236 | |
| 237 | In short, try to minimize the amount of information that users are |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 238 | absolutely required to supply---use sensible defaults whenever |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 239 | possible. Of course, you also want to make your programs reasonably |
| 240 | flexible. That's what options are for. Again, it doesn't matter if |
| 241 | they are entries in a config file, checkboxes in the ``Preferences'' |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 242 | dialog of a GUI, or command-line options---the more options you |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 243 | implement, the more flexible your program is, and the more complicated |
| 244 | its implementation becomes. It's quite easy to overwhelm users (and |
| 245 | yourself!) with too much flexibility, so be careful there. |
| 246 | |
| 247 | \subsection{Basic Usage\label{optparse-basic-usage}} |
| 248 | |
| 249 | While \module{optparse} is quite flexible and powerful, you don't have |
| 250 | to jump through hoops or read reams of documentation to get it working |
| 251 | in basic cases. This document aims to demonstrate some simple usage |
| 252 | patterns that will get you started using \module{optparse} in your |
| 253 | scripts. |
| 254 | |
| 255 | To parse a command line with \module{optparse}, you must create an |
| 256 | \class{OptionParser} instance and populate it. Obviously, you'll have |
| 257 | to import the \class{OptionParser} classes in any script that uses |
| 258 | \module{optparse}: |
| 259 | |
| 260 | \begin{verbatim} |
| 261 | from optparse import OptionParser |
| 262 | \end{verbatim} |
| 263 | |
| 264 | Early on in the main program, create a parser: |
| 265 | |
| 266 | \begin{verbatim} |
| 267 | parser = OptionParser() |
| 268 | \end{verbatim} |
| 269 | |
| 270 | Then you can start populating the parser with options. Each option is |
| 271 | really a set of synonymous option strings; most commonly, you'll have |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 272 | one short option string and one long option string --- |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 273 | e.g. \programopt{-f} and \longprogramopt{file}: |
| 274 | |
| 275 | \begin{verbatim} |
| 276 | parser.add_option("-f", "--file", ...) |
| 277 | \end{verbatim} |
| 278 | |
| 279 | The interesting stuff, of course, is what comes after the option |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 280 | strings. For now, we'll only cover four of the things you can put |
Fred Drake | 3ec4dfd | 2003-05-09 18:18:46 +0000 | [diff] [blame] | 281 | there: \emph{action}, \emph{type}, \emph{dest} (destination), and |
| 282 | \emph{help}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 283 | |
Fred Drake | 3ec4dfd | 2003-05-09 18:18:46 +0000 | [diff] [blame] | 284 | \subsubsection{The \emph{store} action% |
| 285 | \label{optparse-store-action}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 286 | |
| 287 | The action tells \module{optparse} what to do when it sees one of the |
| 288 | option strings for this option on the command-line. For example, the |
Fred Drake | 3ec4dfd | 2003-05-09 18:18:46 +0000 | [diff] [blame] | 289 | action \emph{store} means: take the next argument (or the remainder of |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 290 | the current argument), ensure that it is of the correct type, and |
| 291 | store it to your chosen destination. |
| 292 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 293 | For example, let's fill in the ``...'' of that last option: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 294 | |
| 295 | \begin{verbatim} |
| 296 | parser.add_option("-f", "--file", |
| 297 | action="store", type="string", dest="filename") |
| 298 | \end{verbatim} |
| 299 | |
| 300 | Now let's make up a fake command-line and ask \module{optparse} to |
| 301 | parse it: |
| 302 | |
| 303 | \begin{verbatim} |
| 304 | args = ["-f", "foo.txt"] |
| 305 | (options, args) = parser.parse_args(args) |
| 306 | \end{verbatim} |
| 307 | |
| 308 | (Note that if you don't pass an argument list to |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 309 | \function{parse_args()}, it automatically uses \code{sys.argv[1:]}.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 310 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 311 | When \module{optparse} sees the \programopt{-f}, it consumes the next |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 312 | argument---\code{foo.txt}---and stores it in the \member{filename} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 313 | attribute of a special object. That object is the first return value |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 314 | from \function{parse_args()}, so: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 315 | |
| 316 | \begin{verbatim} |
| 317 | print options.filename |
| 318 | \end{verbatim} |
| 319 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 320 | will print \code{foo.txt}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 321 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 322 | Other option types supported by \module{optparse} are \code{int} and |
| 323 | \code{float}. Here's an option that expects an integer argument: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 324 | |
| 325 | \begin{verbatim} |
| 326 | parser.add_option("-n", type="int", dest="num") |
| 327 | \end{verbatim} |
| 328 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 329 | This example doesn't provide a long option, which is perfectly |
| 330 | acceptable. It also doesn't specify the action---it defaults to |
| 331 | ``store''. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 332 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 333 | Let's parse another fake command-line. This time, we'll jam the option |
| 334 | argument right up against the option, since \programopt{-n42} (one |
| 335 | argument) is equivalent to \programopt{-n 42} (two arguments). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 336 | |
| 337 | \begin{verbatim} |
| 338 | (options, args) = parser.parse_args(["-n42"]) |
| 339 | print options.num |
| 340 | \end{verbatim} |
| 341 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 342 | This prints \code{42}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 343 | |
| 344 | Trying out the ``float'' type is left as an exercise for the reader. |
| 345 | |
| 346 | If you don't specify a type, \module{optparse} assumes ``string''. |
| 347 | Combined with the fact that the default action is ``store'', that |
| 348 | means our first example can be a lot shorter: |
| 349 | |
| 350 | \begin{verbatim} |
| 351 | parser.add_option("-f", "--file", dest="filename") |
| 352 | \end{verbatim} |
| 353 | |
| 354 | If you don't supply a destination, \module{optparse} figures out a |
| 355 | sensible default from the option strings: if the first long option |
| 356 | string is \longprogramopt{foo-bar}, then the default destination is |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 357 | \member{foo_bar}. If there are no long option strings, |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 358 | \module{optparse} looks at the first short option: the default |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 359 | destination for \programopt{-f} is \member{f}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 360 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 361 | Adding types is fairly easy; please refer to |
| 362 | section~\ref{optparse-adding-types}, ``Adding new types.'' |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 363 | |
Fred Drake | 3ec4dfd | 2003-05-09 18:18:46 +0000 | [diff] [blame] | 364 | \subsubsection{Other \emph{store_*} actions% |
| 365 | \label{optparse-other-store-actions}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 366 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 367 | Flag options---set a variable to true or false when a particular |
| 368 | option is seen---are quite common. \module{optparse} supports them |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 369 | with two separate actions, ``store_true'' and ``store_false''. For |
| 370 | example, you might have a \var{verbose} flag that is turned on with |
| 371 | \programopt{-v} and off with \programopt{-q}: |
| 372 | |
| 373 | \begin{verbatim} |
| 374 | parser.add_option("-v", action="store_true", dest="verbose") |
| 375 | parser.add_option("-q", action="store_false", dest="verbose") |
| 376 | \end{verbatim} |
| 377 | |
| 378 | Here we have two different options with the same destination, which is |
| 379 | perfectly OK. (It just means you have to be a bit careful when setting |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 380 | default values---see below.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 381 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 382 | When \module{optparse} sees \programopt{-v} on the command line, it sets |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 383 | \code{options.verbose} to \code{True}; when it sees \programopt{-q}, it |
| 384 | sets \code{options.verbose} to \code{False}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 385 | |
| 386 | \subsubsection{Setting default values\label{optparse-setting-default-values}} |
| 387 | |
| 388 | All of the above examples involve setting some variable (the |
| 389 | ``destination'') when certain command-line options are seen. What |
| 390 | happens if those options are never seen? Since we didn't supply any |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 391 | defaults, they are all set to \code{None}. Sometimes, this is just fine (which |
| 392 | is why it's the default), but sometimes, you want more control. To |
| 393 | address that need, \module{optparse} lets you supply a default value for |
| 394 | each destination, which is assigned before the command-line is parsed. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 395 | |
| 396 | First, consider the verbose/quiet example. If we want |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 397 | \module{optparse} to set \member{verbose} to \code{True} unless |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 398 | \programopt{-q} is seen, then we can do this: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 399 | |
| 400 | \begin{verbatim} |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 401 | parser.add_option("-v", action="store_true", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 402 | parser.add_option("-q", action="store_false", dest="verbose") |
| 403 | \end{verbatim} |
| 404 | |
| 405 | Oddly enough, this is exactly equivalent: |
| 406 | |
| 407 | \begin{verbatim} |
| 408 | parser.add_option("-v", action="store_true", dest="verbose") |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 409 | parser.add_option("-q", action="store_false", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 410 | \end{verbatim} |
| 411 | |
| 412 | Those are equivalent because you're supplying a default value for the |
| 413 | option's \emph{destination}, and these two options happen to have the same |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 414 | destination (the \member{verbose} variable). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 415 | |
| 416 | Consider this: |
| 417 | |
| 418 | \begin{verbatim} |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 419 | parser.add_option("-v", action="store_true", dest="verbose", default=False) |
| 420 | parser.add_option("-q", action="store_false", dest="verbose", default=True) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 421 | \end{verbatim} |
| 422 | |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 423 | Again, the default value for \member{verbose} will be \code{True}: the last |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 424 | default value supplied for any particular destination is the one that |
| 425 | counts. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 426 | |
| 427 | \subsubsection{Generating help\label{optparse-generating-help}} |
| 428 | |
| 429 | The last feature that you will use in every script is |
| 430 | \module{optparse}'s ability to generate help messages. All you have |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 431 | to do is supply a \var{help} argument when you add an option. Let's |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 432 | create a new parser and populate it with user-friendly (documented) |
| 433 | options: |
| 434 | |
| 435 | \begin{verbatim} |
| 436 | usage = "usage: %prog [options] arg1 arg2" |
| 437 | parser = OptionParser(usage=usage) |
| 438 | parser.add_option("-v", "--verbose", |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 439 | action="store_true", dest="verbose", default=True, |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 440 | help="make lots of noise [default]") |
| 441 | parser.add_option("-q", "--quiet", |
| 442 | action="store_false", dest="verbose", |
| 443 | help="be vewwy quiet (I'm hunting wabbits)") |
| 444 | parser.add_option("-f", "--file", dest="filename", |
| 445 | metavar="FILE", help="write output to FILE"), |
| 446 | parser.add_option("-m", "--mode", |
| 447 | default="intermediate", |
| 448 | help="interaction mode: one of 'novice', " |
| 449 | "'intermediate' [default], 'expert'") |
| 450 | \end{verbatim} |
| 451 | |
| 452 | If \module{optparse} encounters either \programopt{-h} or |
Greg Ward | b4e3319 | 2003-05-03 19:16:36 +0000 | [diff] [blame] | 453 | \longprogramopt{help} on the command-line, or if you just call |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 454 | \method{parser.print_help()}, it prints the following to stdout: |
| 455 | |
| 456 | \begin{verbatim} |
| 457 | usage: <yourscript> [options] arg1 arg2 |
| 458 | |
| 459 | options: |
| 460 | -h, --help show this help message and exit |
| 461 | -v, --verbose make lots of noise [default] |
| 462 | -q, --quiet be vewwy quiet (I'm hunting wabbits) |
| 463 | -fFILE, --file=FILE write output to FILE |
| 464 | -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate' |
| 465 | [default], 'expert' |
| 466 | \end{verbatim} |
| 467 | |
| 468 | There's a lot going on here to help \module{optparse} generate the |
| 469 | best possible help message: |
| 470 | |
| 471 | \begin{itemize} |
| 472 | \item the script defines its own usage message: |
| 473 | |
| 474 | \begin{verbatim} |
| 475 | usage = "usage: %prog [options] arg1 arg2" |
| 476 | \end{verbatim} |
| 477 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 478 | \module{optparse} expands \samp{\%prog} in the usage string to the name of the |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 479 | current script, i.e. \code{os.path.basename(sys.argv[0])}. The |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 480 | expanded string is then printed before the detailed option help. |
| 481 | |
| 482 | If you don't supply a usage string, \module{optparse} uses a bland but |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 483 | sensible default: \code{"usage: \%prog [options]"}, which is fine if your |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 484 | script doesn't take any positional arguments. |
| 485 | |
| 486 | \item every option defines a help string, and doesn't worry about |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 487 | line-wrapping---\module{optparse} takes care of wrapping lines and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 488 | making the help output look good. |
| 489 | |
| 490 | \item options that take a value indicate this fact in their |
| 491 | automatically-generated help message, e.g. for the ``mode'' option: |
| 492 | |
| 493 | \begin{verbatim} |
| 494 | -mMODE, --mode=MODE |
| 495 | \end{verbatim} |
| 496 | |
| 497 | Here, ``MODE'' is called the meta-variable: it stands for the argument |
| 498 | that the user is expected to supply to |
| 499 | \programopt{-m}/\longprogramopt{mode}. By default, \module{optparse} |
| 500 | converts the destination variable name to uppercase and uses that for |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 501 | the meta-variable. Sometimes, that's not what you want---for |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 502 | example, the \var{filename} option explicitly sets |
| 503 | \code{metavar="FILE"}, resulting in this automatically-generated |
| 504 | option description: |
| 505 | |
| 506 | \begin{verbatim} |
| 507 | -fFILE, --file=FILE |
| 508 | \end{verbatim} |
| 509 | |
| 510 | This is important for more than just saving space, though: the |
| 511 | manually written help text uses the meta-variable ``FILE'', to clue |
| 512 | the user in that there's a connection between the formal syntax |
| 513 | ``-fFILE'' and the informal semantic description ``write output to |
| 514 | FILE''. This is a simple but effective way to make your help text a |
| 515 | lot clearer and more useful for end users. |
| 516 | \end{itemize} |
| 517 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 518 | When dealing with many options, it is convenient to group these |
| 519 | options for better help output. An \class{OptionParser} can contain |
| 520 | several option groups, each of which can contain several options. |
| 521 | |
| 522 | Continuing with the parser defined above, adding an |
| 523 | \class{OptionGroup} to a parser is easy: |
| 524 | |
| 525 | \begin{verbatim} |
| 526 | group = OptionGroup(parser, "Dangerous Options", |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 527 | "Caution: use these options at your own risk. " |
| 528 | "It is believed that some of them bite.") |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 529 | group.add_option("-g", action="store_true", help="Group option.") |
| 530 | parser.add_option_group(group) |
| 531 | \end{verbatim} |
| 532 | |
| 533 | This would result in the following help output: |
| 534 | |
| 535 | \begin{verbatim} |
| 536 | usage: [options] arg1 arg2 |
| 537 | |
| 538 | options: |
| 539 | -h, --help show this help message and exit |
| 540 | -v, --verbose make lots of noise [default] |
| 541 | -q, --quiet be vewwy quiet (I'm hunting wabbits) |
| 542 | -fFILE, --file=FILE write output to FILE |
| 543 | -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate' |
| 544 | [default], 'expert' |
| 545 | |
| 546 | Dangerous Options: |
| 547 | Caution: use of these options is at your own risk. It is believed that |
| 548 | some of them bite. |
| 549 | -g Group option. |
| 550 | \end{verbatim} |
| 551 | |
| 552 | |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 553 | \subsubsection{Print a version number\label{optparse-print-version}} |
| 554 | |
| 555 | Similar to the brief usage string, \module{optparse} can also print a |
| 556 | version string for your program. You have to supply the string, as |
| 557 | the \var{version} argument to \class{OptionParser}: |
| 558 | |
| 559 | \begin{verbatim} |
| 560 | parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") |
| 561 | \end{verbatim} |
| 562 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 563 | \var{version} can contain anything you like; \code{\%prog} is expanded |
| 564 | in \var{version} just as with \var{usage}. When you supply it, |
| 565 | \module{optparse} automatically adds a \longprogramopt{version} option |
| 566 | to your parser. If it encounters this option on the command line, it |
| 567 | expands your \var{version} string (by replacing \code{\%prog}), prints |
| 568 | it to stdout, and exits. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 569 | |
| 570 | For example, if your script is called /usr/bin/foo, a user might do: |
| 571 | |
| 572 | \begin{verbatim} |
| 573 | $ /usr/bin/foo --version |
| 574 | foo 1.0 |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 575 | \end{verbatim} % $ (avoid confusing emacs) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 576 | |
| 577 | \subsubsection{Error-handling\label{optparse-error-handling}} |
| 578 | |
| 579 | The one thing you need to know for basic usage is how |
| 580 | \module{optparse} behaves when it encounters an error on the |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 581 | command-line---e.g. \programopt{-n 4x} where \programopt{-n} is an |
| 582 | integer-valued option. In this case, \module{optparse} prints your |
| 583 | usage message to stderr, followed by a useful and human-readable error |
| 584 | message. Then it terminates (calls \function{sys.exit()}) with a |
| 585 | non-zero exit status. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 586 | |
| 587 | If you don't like this, subclass \class{OptionParser} and override the |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 588 | \method{error()} method. See section~\ref{optparse-extending}, |
| 589 | ``Extending \module{optparse}.'' |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 590 | |
| 591 | \subsubsection{Putting it all together\label{optparse-basic-summary}} |
| 592 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 593 | Here's what \module{optparse}-based scripts typically look like: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 594 | |
| 595 | \begin{verbatim} |
| 596 | from optparse import OptionParser |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 597 | [...] |
| 598 | def main(): |
| 599 | usage = "usage: \%prog [-f] [-v] [-q] firstarg secondarg" |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 600 | parser = OptionParser(usage) |
| 601 | parser.add_option("-f", "--file", type="string", dest="filename", |
| 602 | help="read data from FILENAME") |
| 603 | parser.add_option("-v", "--verbose", |
| 604 | action="store_true", dest="verbose") |
| 605 | parser.add_option("-q", "--quiet", |
| 606 | action="store_false", dest="verbose") |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 607 | |
| 608 | (options, args) = parser.parse_args() |
| 609 | if len(args) != 1: |
| 610 | parser.error("incorrect number of arguments") |
| 611 | |
| 612 | if options.verbose: |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 613 | print "reading \%s..." \% options.filename |
| 614 | [... go to work ...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 615 | |
| 616 | if __name__ == "__main__": |
| 617 | main() |
| 618 | \end{verbatim} |
| 619 | |
| 620 | \subsection{Advanced Usage\label{optparse-advanced-usage}} |
| 621 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 622 | \subsubsection{Creating and populating the |
| 623 | parser\label{optparse-creating-the-parser}} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 624 | |
| 625 | There are several ways to populate the parser with options. One way |
| 626 | is to pass a list of \class{Options} to the \class{OptionParser} |
| 627 | constructor: |
| 628 | |
| 629 | \begin{verbatim} |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 630 | from optparse import OptionParser, make_option |
| 631 | [...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 632 | parser = OptionParser(option_list=[ |
| 633 | make_option("-f", "--filename", |
| 634 | action="store", type="string", dest="filename"), |
| 635 | make_option("-q", "--quiet", |
| 636 | action="store_false", dest="verbose")]) |
| 637 | \end{verbatim} |
| 638 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 639 | (\function{make_option()} is a factory function for generating |
| 640 | \class{Option} objects.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 641 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 642 | For long option lists, it may be more convenient/readable to create the |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 643 | list separately: |
| 644 | |
| 645 | \begin{verbatim} |
| 646 | option_list = [make_option("-f", "--filename", |
| 647 | action="store", type="string", dest="filename"), |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 648 | [... more options ...] |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 649 | make_option("-q", "--quiet", |
| 650 | action="store_false", dest="verbose")] |
| 651 | parser = OptionParser(option_list=option_list) |
| 652 | \end{verbatim} |
| 653 | |
| 654 | Or, you can use the \method{add_option()} method of |
| 655 | \class{OptionParser} to add options one-at-a-time: |
| 656 | |
| 657 | \begin{verbatim} |
| 658 | parser = OptionParser() |
| 659 | parser.add_option("-f", "--filename", |
| 660 | action="store", type="string", dest="filename") |
| 661 | parser.add_option("-q", "--quiet", |
| 662 | action="store_false", dest="verbose") |
| 663 | \end{verbatim} |
| 664 | |
| 665 | This method makes it easier to track down exceptions raised by the |
| 666 | \class{Option} constructor, which are common because of the complicated |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 667 | interdependencies among the various keyword arguments. (If you get it |
| 668 | wrong, \module{optparse} raises \exception{OptionError}.) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 669 | |
| 670 | \method{add_option()} can be called in one of two ways: |
| 671 | |
| 672 | \begin{itemize} |
| 673 | \item pass it an \class{Option} instance (as returned by \function{make_option()}) |
| 674 | \item pass it any combination of positional and keyword arguments that |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 675 | are acceptable to \function{make_option()} (i.e., to the \class{Option} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 676 | constructor), and it will create the \class{Option} instance for you |
| 677 | (shown above). |
| 678 | \end{itemize} |
| 679 | |
| 680 | \subsubsection{Defining options\label{optparse-defining-options}} |
| 681 | |
| 682 | Each \class{Option} instance represents a set of synonymous |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 683 | command-line options, i.e. options that have the same meaning and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 684 | effect, but different spellings. You can specify any number of short |
| 685 | or long option strings, but you must specify at least one option |
| 686 | string. |
| 687 | |
| 688 | To define an option with only a short option string: |
| 689 | |
| 690 | \begin{verbatim} |
| 691 | make_option("-f", ...) |
| 692 | \end{verbatim} |
| 693 | |
| 694 | And to define an option with only a long option string: |
| 695 | |
| 696 | \begin{verbatim} |
| 697 | make_option("--foo", ...) |
| 698 | \end{verbatim} |
| 699 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 700 | The ``...'' represents a set of keyword arguments that define attributes |
| 701 | of the \class{Option} object. The rules governing which keyword args |
| 702 | you must supply for a given \class{Option} are fairly complicated, but |
| 703 | you always have to supply \emph{some}. If you get it wrong, |
| 704 | \module{optparse} raises an \exception{OptionError} exception explaining |
| 705 | your mistake. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 706 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 707 | The most important attribute of an option is its action, i.e. what to do |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 708 | when we encounter this option on the command-line. The possible actions |
| 709 | are: |
| 710 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 711 | \begin{tableii}{l|l}{code}{Action}{Meaning} |
| 712 | \lineii{store}{store this option's argument (default)} |
| 713 | \lineii{store_const}{store a constant value} |
| 714 | \lineii{store_true}{store a true value} |
| 715 | \lineii{store_false}{store a false value} |
| 716 | \lineii{append}{append this option's argument to a list} |
| 717 | \lineii{count}{increment a counter by one} |
| 718 | \lineii{callback}{call a specified function} |
| 719 | \lineii{help}{print a usage message including all options and the |
| 720 | documentation for them} |
| 721 | \end{tableii} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 722 | |
| 723 | (If you don't supply an action, the default is ``store''. For this |
| 724 | action, you may also supply \var{type} and \var{dest} keywords; see |
| 725 | below.) |
| 726 | |
| 727 | As you can see, most actions involve storing or updating a value |
| 728 | somewhere. \module{optparse} always creates a particular object (an |
| 729 | instance of the \class{Values} class) specifically for this |
| 730 | purpose. Option arguments (and various other values) are stored as |
| 731 | attributes of this object, according to the \var{dest} (destination) |
| 732 | argument to \function{make_option()}/\method{add_option()}. |
| 733 | |
| 734 | For example, when you call: |
| 735 | |
| 736 | \begin{verbatim} |
| 737 | parser.parse_args() |
| 738 | \end{verbatim} |
| 739 | |
| 740 | one of the first things \module{optparse} does is create a |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 741 | \code{values} object: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 742 | |
| 743 | \begin{verbatim} |
| 744 | values = Values() |
| 745 | \end{verbatim} |
| 746 | |
| 747 | If one of the options in this parser is defined with: |
| 748 | |
| 749 | \begin{verbatim} |
| 750 | make_option("-f", "--file", action="store", type="string", dest="filename") |
| 751 | \end{verbatim} |
| 752 | |
| 753 | and the command-line being parsed includes any of the following: |
| 754 | |
| 755 | \begin{verbatim} |
| 756 | -ffoo |
| 757 | -f foo |
| 758 | --file=foo |
| 759 | --file foo |
| 760 | \end{verbatim} |
| 761 | |
| 762 | then \module{optparse}, on seeing the \programopt{-f} or |
| 763 | \longprogramopt{file} option, will do the equivalent of this: |
| 764 | |
| 765 | \begin{verbatim} |
| 766 | values.filename = "foo" |
| 767 | \end{verbatim} |
| 768 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 769 | Clearly, the \var{type} and \var{dest} arguments are almost |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 770 | as important as \var{action}. \var{action} is the only attribute that |
Greg Ward | b4e3319 | 2003-05-03 19:16:36 +0000 | [diff] [blame] | 771 | is meaningful for \emph{all} options, though, so it is the most |
| 772 | important. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 773 | |
| 774 | \subsubsection{Option actions\label{optparse-option-actions}} |
| 775 | |
| 776 | The various option actions all have slightly different requirements |
| 777 | and effects. Except for the ``help'' action, you must supply at least |
| 778 | one other keyword argument when creating the \class{Option}; the exact |
| 779 | requirements for each action are listed here. |
| 780 | |
| 781 | \begin{definitions} |
| 782 | \term{store} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}] |
| 783 | |
| 784 | The option must be followed by an argument, which is converted to a |
| 785 | value according to \var{type} and stored in \var{dest}. If |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 786 | \code{nargs > 1}, multiple arguments will be consumed from the command |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 787 | line; all will be converted according to \var{type} and stored to |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 788 | \var{dest} as a tuple. See section~\ref{optparse-option-types}, |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 789 | ``Option types,'' below. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 790 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 791 | If \var{choices} (a sequence of strings) is supplied, the type |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 792 | defaults to ``choice''. |
| 793 | |
| 794 | If \var{type} is not supplied, it defaults to ``string''. |
| 795 | |
| 796 | If \var{dest} is not supplied, \module{optparse} derives a |
| 797 | destination from the first long option strings (e.g., |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 798 | \longprogramopt{foo-bar} becomes \member{foo_bar}). If there are no long |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 799 | option strings, \module{optparse} derives a destination from the first |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 800 | short option string (e.g., \programopt{-f} becomes \member{f}). |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 801 | |
| 802 | Example: |
| 803 | |
| 804 | \begin{verbatim} |
| 805 | make_option("-f") |
| 806 | make_option("-p", type="float", nargs=3, dest="point") |
| 807 | \end{verbatim} |
| 808 | |
| 809 | Given the following command line: |
| 810 | |
| 811 | \begin{verbatim} |
| 812 | -f foo.txt -p 1 -3.5 4 -fbar.txt |
| 813 | \end{verbatim} |
| 814 | |
| 815 | \module{optparse} will set: |
| 816 | |
| 817 | \begin{verbatim} |
| 818 | values.f = "bar.txt" |
| 819 | values.point = (1.0, -3.5, 4.0) |
| 820 | \end{verbatim} |
| 821 | |
| 822 | (Actually, \member{values.f} will be set twice, but only the second |
| 823 | time is visible in the end.) |
| 824 | |
| 825 | \term{store_const} [required: \var{const}, \var{dest}] |
| 826 | |
| 827 | The \var{const} value supplied to the \class{Option} constructor is |
| 828 | stored in \var{dest}. |
| 829 | |
| 830 | Example: |
| 831 | |
| 832 | \begin{verbatim} |
| 833 | make_option("-q", "--quiet", |
| 834 | action="store_const", const=0, dest="verbose"), |
| 835 | make_option("-v", "--verbose", |
| 836 | action="store_const", const=1, dest="verbose"), |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 837 | make_option("--noisy", |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 838 | action="store_const", const=2, dest="verbose"), |
| 839 | \end{verbatim} |
| 840 | |
| 841 | If \longprogramopt{noisy} is seen, \module{optparse} will set: |
| 842 | |
| 843 | \begin{verbatim} |
| 844 | values.verbose = 2 |
| 845 | \end{verbatim} |
| 846 | |
| 847 | \term{store_true} [required: \var{dest}] |
| 848 | |
Greg Ward | 1f53517 | 2003-05-03 20:13:08 +0000 | [diff] [blame] | 849 | A special case of ``store_const'' that stores \code{True} to \var{dest}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 850 | |
| 851 | \term{store_false} [required: \var{dest}] |
| 852 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 853 | Like ``store_true'', but stores \code{False} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 854 | |
| 855 | Example: |
| 856 | |
| 857 | \begin{verbatim} |
| 858 | make_option(None, "--clobber", action="store_true", dest="clobber") |
| 859 | make_option(None, "--no-clobber", action="store_false", dest="clobber") |
| 860 | \end{verbatim} |
| 861 | |
| 862 | \term{append} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}] |
| 863 | |
| 864 | The option must be followed by an argument, which is appended to the |
| 865 | list in \var{dest}. If no default value for \var{dest} is supplied |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 866 | (i.e. the default is \code{None}), an empty list is automatically created when |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 867 | \module{optparse} first encounters this option on the command-line. |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 868 | If \code{nargs > 1}, multiple arguments are consumed, and a tuple of |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 869 | length \var{nargs} is appended to \var{dest}. |
| 870 | |
| 871 | The defaults for \var{type} and \var{dest} are the same as for the |
| 872 | ``store'' action. |
| 873 | |
| 874 | Example: |
| 875 | |
| 876 | \begin{verbatim} |
| 877 | make_option("-t", "--tracks", action="append", type="int") |
| 878 | \end{verbatim} |
| 879 | |
| 880 | If \programopt{-t3} is seen on the command-line, \module{optparse} does the equivalent of: |
| 881 | |
| 882 | \begin{verbatim} |
| 883 | values.tracks = [] |
| 884 | values.tracks.append(int("3")) |
| 885 | \end{verbatim} |
| 886 | |
Greg Ward | b4e3319 | 2003-05-03 19:16:36 +0000 | [diff] [blame] | 887 | If, a little later on, \longprogramopt{tracks=4} is seen, it does: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 888 | |
| 889 | \begin{verbatim} |
| 890 | values.tracks.append(int("4")) |
| 891 | \end{verbatim} |
| 892 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 893 | See ``Error handling'' (section~\ref{optparse-error-handling}) for |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 894 | information on how \module{optparse} deals with something like |
Greg Ward | b4e3319 | 2003-05-03 19:16:36 +0000 | [diff] [blame] | 895 | \longprogramopt{tracks=x}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 896 | |
| 897 | \term{count} [required: \var{dest}] |
| 898 | |
| 899 | Increment the integer stored at \var{dest}. \var{dest} is set to zero |
| 900 | before being incremented the first time (unless you supply a default |
| 901 | value). |
| 902 | |
| 903 | Example: |
| 904 | |
| 905 | \begin{verbatim} |
| 906 | make_option("-v", action="count", dest="verbosity") |
| 907 | \end{verbatim} |
| 908 | |
| 909 | The first time \programopt{-v} is seen on the command line, |
| 910 | \module{optparse} does the equivalent of: |
| 911 | |
| 912 | \begin{verbatim} |
| 913 | values.verbosity = 0 |
| 914 | values.verbosity += 1 |
| 915 | \end{verbatim} |
| 916 | |
| 917 | Every subsequent occurrence of \programopt{-v} results in: |
| 918 | |
| 919 | \begin{verbatim} |
| 920 | values.verbosity += 1 |
| 921 | \end{verbatim} |
| 922 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 923 | \term{callback} [required: \var{callback}; |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 924 | relevant: \var{type}, \var{nargs}, \var{callback_args}, |
| 925 | \var{callback_kwargs}] |
| 926 | |
| 927 | Call the function specified by \var{callback}. The signature of |
| 928 | this function should be: |
| 929 | |
| 930 | \begin{verbatim} |
| 931 | func(option : Option, |
| 932 | opt : string, |
| 933 | value : any, |
| 934 | parser : OptionParser, |
| 935 | *args, **kwargs) |
| 936 | \end{verbatim} |
| 937 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 938 | Callback options are covered in detail in |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 939 | section~\ref{optparse-callback-options}, ``Callback Options.'' |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 940 | |
| 941 | \term{help} [required: none] |
| 942 | |
| 943 | Prints a complete help message for all the options in the current |
| 944 | option parser. The help message is constructed from the \var{usage} |
| 945 | string passed to \class{OptionParser}'s constructor and the \var{help} |
| 946 | string passed to every option. |
| 947 | |
| 948 | If no \var{help} string is supplied for an option, it will still be |
| 949 | listed in the help message. To omit an option entirely, use the |
| 950 | special value \constant{optparse.SUPPRESS_HELP}. |
| 951 | |
| 952 | Example: |
| 953 | |
| 954 | \begin{verbatim} |
| 955 | from optparse import Option, OptionParser, SUPPRESS_HELP |
| 956 | |
| 957 | usage = "usage: %prog [options]" |
| 958 | parser = OptionParser(usage, option_list=[ |
| 959 | make_option("-h", "--help", action="help"), |
| 960 | make_option("-v", action="store_true", dest="verbose", |
| 961 | help="Be moderately verbose") |
| 962 | make_option("--file", dest="filename", |
| 963 | help="Input file to read data from"), |
| 964 | make_option("--secret", help=SUPPRESS_HELP) |
Raymond Hettinger | 52136a8 | 2003-05-10 03:35:37 +0000 | [diff] [blame] | 965 | ]) |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 966 | \end{verbatim} |
| 967 | |
Greg Ward | b4e3319 | 2003-05-03 19:16:36 +0000 | [diff] [blame] | 968 | If \module{optparse} sees either \programopt{-h} or |
| 969 | \longprogramopt{help} on the command line, it will print something |
| 970 | like the following help message to stdout: |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 971 | |
| 972 | \begin{verbatim} |
| 973 | usage: <yourscript> [options] |
| 974 | |
| 975 | options: |
| 976 | -h, --help Show this help message and exit |
| 977 | -v Be moderately verbose |
| 978 | --file=FILENAME Input file to read data from |
| 979 | \end{verbatim} |
| 980 | |
| 981 | After printing the help message, \module{optparse} terminates your process |
| 982 | with \code{sys.exit(0)}. |
| 983 | |
| 984 | \term{version} [required: none] |
| 985 | |
| 986 | Prints the version number supplied to the \class{OptionParser} to |
| 987 | stdout and exits. The version number is actually formatted and |
| 988 | printed by the \method{print_version()} method of |
| 989 | \class{OptionParser}. Generally only relevant if the \var{version} |
| 990 | argument is supplied to the \class{OptionParser} constructor. |
| 991 | \end{definitions} |
| 992 | |
| 993 | \subsubsection{Option types\label{optparse-option-types}} |
| 994 | |
| 995 | \module{optparse} supports six option types out of the box: \dfn{string}, |
| 996 | \dfn{int}, \dfn{long}, \dfn{choice}, \dfn{float} and \dfn{complex}. |
| 997 | (Of these, string, int, float, and choice are the most commonly used |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 998 | ---long and complex are there mainly for completeness.) It's easy to |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 999 | add new option types by subclassing the \class{Option} class; see |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1000 | section~\ref{optparse-extending}, ``Extending \module{optparse}.'' |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1001 | |
| 1002 | Arguments to string options are not checked or converted in any way: |
| 1003 | the text on the command line is stored in the destination (or passed |
| 1004 | to the callback) as-is. |
| 1005 | |
| 1006 | Integer arguments are passed to \function{int()} to convert them to |
| 1007 | Python integers. If \function{int()} fails, so will |
| 1008 | \module{optparse}, although with a more useful error message. |
| 1009 | Internally, \module{optparse} raises \exception{OptionValueError} in |
| 1010 | \function{optparse.check_builtin()}; at a higher level (in |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1011 | \class{OptionParser}), \module{optparse} catches this exception and |
| 1012 | terminates your program with a useful error message. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1013 | |
| 1014 | Likewise, float arguments are passed to \function{float()} for |
| 1015 | conversion, long arguments to \function{long()}, and complex arguments |
| 1016 | to \function{complex()}. Apart from that, they are handled |
| 1017 | identically to integer arguments. |
| 1018 | |
| 1019 | Choice options are a subtype of string options. A master list or |
| 1020 | tuple of choices (strings) must be passed to the option constructor |
| 1021 | (\function{make_option()} or \method{OptionParser.add_option()}) as |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1022 | the \var{choices} keyword argument. Choice option arguments are |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1023 | compared against this master list in |
| 1024 | \function{optparse.check_choice()}, and \exception{OptionValueError} |
| 1025 | is raised if an unknown string is given. |
| 1026 | |
| 1027 | \subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating}} |
| 1028 | |
| 1029 | Sometimes, it's useful to poke around your option parser and see what's |
| 1030 | there. \class{OptionParser} provides a couple of methods to help you out: |
| 1031 | |
| 1032 | \begin{methoddesc}{has_option}{opt_str} |
| 1033 | Given an option string such as \programopt{-q} or |
| 1034 | \longprogramopt{verbose}, returns true if the \class{OptionParser} |
| 1035 | has an option with that option string. |
| 1036 | \end{methoddesc} |
| 1037 | |
| 1038 | \begin{methoddesc}{get_option}{opt_str} |
| 1039 | Returns the \class{Option} instance that implements the option |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1040 | string you supplied, or \code{None} if no options implement it. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1041 | \end{methoddesc} |
| 1042 | |
| 1043 | \begin{methoddesc}{remove_option}{opt_str} |
| 1044 | If the \class{OptionParser} has an option corresponding to |
| 1045 | \var{opt_str}, that option is removed. If that option provided |
| 1046 | any other option strings, all of those option strings become |
| 1047 | invalid. |
| 1048 | |
| 1049 | If \var{opt_str} does not occur in any option belonging to this |
| 1050 | \class{OptionParser}, raises \exception{ValueError}. |
| 1051 | \end{methoddesc} |
| 1052 | |
| 1053 | \subsubsection{Conflicts between options\label{optparse-conflicts}} |
| 1054 | |
| 1055 | If you're not careful, it's easy to define conflicting options: |
| 1056 | |
| 1057 | \begin{verbatim} |
| 1058 | parser.add_option("-n", "--dry-run", ...) |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1059 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1060 | parser.add_option("-n", "--noisy", ...) |
| 1061 | \end{verbatim} |
| 1062 | |
| 1063 | (This is even easier to do if you've defined your own |
| 1064 | \class{OptionParser} subclass with some standard options.) |
| 1065 | |
| 1066 | On the assumption that this is usually a mistake, \module{optparse} |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1067 | raises an exception (\exception{OptionConflictError}) by default when |
| 1068 | this happens. Since this is an easily-fixed programming error, you |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1069 | shouldn't try to catch this exception---fix your mistake and get on |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1070 | with life. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1071 | |
| 1072 | Sometimes, you want newer options to deliberately replace the option |
| 1073 | strings used by older options. You can achieve this by calling: |
| 1074 | |
| 1075 | \begin{verbatim} |
| 1076 | parser.set_conflict_handler("resolve") |
| 1077 | \end{verbatim} |
| 1078 | |
| 1079 | which instructs \module{optparse} to resolve option conflicts |
| 1080 | intelligently. |
| 1081 | |
| 1082 | Here's how it works: every time you add an option, \module{optparse} |
| 1083 | checks for conflicts with previously-added options. If it finds any, |
| 1084 | it invokes the conflict-handling mechanism you specify either to the |
| 1085 | \class{OptionParser} constructor: |
| 1086 | |
| 1087 | \begin{verbatim} |
| 1088 | parser = OptionParser(..., conflict_handler="resolve") |
| 1089 | \end{verbatim} |
| 1090 | |
| 1091 | or via the \method{set_conflict_handler()} method. |
| 1092 | |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1093 | The default conflict-handling mechanism is \code{error}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1094 | |
| 1095 | Here's an example: first, define an \class{OptionParser} set to |
| 1096 | resolve conflicts intelligently: |
| 1097 | |
| 1098 | \begin{verbatim} |
| 1099 | parser = OptionParser(conflict_handler="resolve") |
| 1100 | \end{verbatim} |
| 1101 | |
| 1102 | Now add all of our options: |
| 1103 | |
| 1104 | \begin{verbatim} |
| 1105 | parser.add_option("-n", "--dry-run", ..., help="original dry-run option") |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1106 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1107 | parser.add_option("-n", "--noisy", ..., help="be noisy") |
| 1108 | \end{verbatim} |
| 1109 | |
| 1110 | At this point, \module{optparse} detects that a previously-added option is already |
| 1111 | using the \programopt{-n} option string. Since \code{conflict_handler |
| 1112 | == "resolve"}, it resolves the situation by removing \programopt{-n} |
| 1113 | from the earlier option's list of option strings. Now, |
| 1114 | \longprogramopt{dry-run} is the only way for the user to activate that |
| 1115 | option. If the user asks for help, the help message will reflect |
| 1116 | that, e.g.: |
| 1117 | |
| 1118 | \begin{verbatim} |
| 1119 | options: |
| 1120 | --dry-run original dry-run option |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1121 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1122 | -n, --noisy be noisy |
| 1123 | \end{verbatim} |
| 1124 | |
| 1125 | Note that it's possible to whittle away the option strings for a |
| 1126 | previously-added option until there are none left, and the user has no |
| 1127 | way of invoking that option from the command-line. In that case, |
| 1128 | \module{optparse} removes that option completely, so it doesn't show |
| 1129 | up in help text or anywhere else. E.g. if we carry on with our |
| 1130 | existing \class{OptionParser}: |
| 1131 | |
| 1132 | \begin{verbatim} |
| 1133 | parser.add_option("--dry-run", ..., help="new dry-run option") |
| 1134 | \end{verbatim} |
| 1135 | |
| 1136 | At this point, the first \programopt{-n}/\longprogramopt{dry-run} |
| 1137 | option is no longer accessible, so \module{optparse} removes it. If |
| 1138 | the user asks for help, they'll get something like this: |
| 1139 | |
| 1140 | \begin{verbatim} |
| 1141 | options: |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1142 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1143 | -n, --noisy be noisy |
| 1144 | --dry-run new dry-run option |
| 1145 | \end{verbatim} |
| 1146 | |
| 1147 | \subsection{Callback Options\label{optparse-callback-options}} |
| 1148 | |
| 1149 | If \module{optparse}'s built-in actions and types just don't fit the |
| 1150 | bill for you, but it's not worth extending \module{optparse} to define |
| 1151 | your own actions or types, you'll probably need to define a callback |
| 1152 | option. Defining callback options is quite easy; the tricky part is |
| 1153 | writing a good callback (the function that is called when |
| 1154 | \module{optparse} encounters the option on the command line). |
| 1155 | |
| 1156 | \subsubsection{Defining a callback option\label{optparse-defining-callback-option}} |
| 1157 | |
| 1158 | As always, you can define a callback option either by directly |
| 1159 | instantiating the \class{Option} class, or by using the |
| 1160 | \method{add_option()} method of your \class{OptionParser} object. The |
| 1161 | only option attribute you must specify is \var{callback}, the function |
| 1162 | to call: |
| 1163 | |
| 1164 | \begin{verbatim} |
| 1165 | parser.add_option("-c", callback=my_callback) |
| 1166 | \end{verbatim} |
| 1167 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1168 | Note that you supply a function object here---so you must have |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1169 | already defined a function \function{my_callback()} when you define |
| 1170 | the callback option. In this simple case, \module{optparse} knows |
| 1171 | nothing about the arguments the \programopt{-c} option expects to |
| 1172 | take. Usually, this means that the option doesn't take any arguments |
| 1173 | -- the mere presence of \programopt{-c} on the command-line is all it |
| 1174 | needs to know. In some circumstances, though, you might want your |
| 1175 | callback to consume an arbitrary number of command-line arguments. |
| 1176 | This is where writing callbacks gets tricky; it's covered later in |
| 1177 | this document. |
| 1178 | |
| 1179 | There are several other option attributes that you can supply when you |
| 1180 | define an option attribute: |
| 1181 | |
| 1182 | \begin{definitions} |
| 1183 | \term{type} |
| 1184 | has its usual meaning: as with the ``store'' or ``append'' actions, it |
| 1185 | instructs \module{optparse} to consume one argument that must be |
| 1186 | convertible to \var{type}. Rather than storing the value(s) anywhere, |
| 1187 | though, \module{optparse} converts it to \var{type} and passes it to |
| 1188 | your callback function. |
| 1189 | |
| 1190 | \term{nargs} |
| 1191 | also has its usual meaning: if it is supplied and \samp{nargs > 1}, |
| 1192 | \module{optparse} will consume \var{nargs} arguments, each of which |
| 1193 | must be convertible to \var{type}. It then passes a tuple of |
| 1194 | converted values to your callback. |
| 1195 | |
| 1196 | \term{callback_args} |
| 1197 | a tuple of extra positional arguments to pass to the callback. |
| 1198 | |
| 1199 | \term{callback_kwargs} |
| 1200 | a dictionary of extra keyword arguments to pass to the callback. |
| 1201 | \end{definitions} |
| 1202 | |
| 1203 | \subsubsection{How callbacks are called\label{optparse-callbacks-called}} |
| 1204 | |
| 1205 | All callbacks are called as follows: |
| 1206 | |
| 1207 | \begin{verbatim} |
| 1208 | func(option, opt, value, parser, *args, **kwargs) |
| 1209 | \end{verbatim} |
| 1210 | |
| 1211 | where |
| 1212 | |
| 1213 | \begin{definitions} |
| 1214 | \term{option} |
| 1215 | is the \class{Option} instance that's calling the callback. |
| 1216 | |
| 1217 | \term{opt} |
| 1218 | is the option string seen on the command-line that's triggering the |
| 1219 | callback. (If an abbreviated long option was used, \var{opt} will be |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 1220 | the full, canonical option string---for example, if the user puts |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1221 | \longprogramopt{foo} on the command-line as an abbreviation for |
| 1222 | \longprogramopt{foobar}, then \var{opt} will be |
| 1223 | \longprogramopt{foobar}.) |
| 1224 | |
| 1225 | \term{value} |
| 1226 | is the argument to this option seen on the command-line. |
| 1227 | \module{optparse} will only expect an argument if \var{type} is |
| 1228 | set; the type of \var{value} will be the type implied by the |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1229 | option's type (see~\ref{optparse-option-types}, ``Option types''). If |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1230 | \var{type} for this option is \code{None} (no argument expected), then |
| 1231 | \var{value} will be \code{None}. If \samp{nargs > 1}, \var{value} will |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1232 | be a tuple of values of the appropriate type. |
| 1233 | |
| 1234 | \term{parser} |
| 1235 | is the \class{OptionParser} instance driving the whole thing, mainly |
| 1236 | useful because you can access some other interesting data through it, |
| 1237 | as instance attributes: |
| 1238 | |
| 1239 | \begin{definitions} |
| 1240 | \term{parser.rargs} |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1241 | the current remaining argument list, i.e. with \var{opt} (and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1242 | \var{value}, if any) removed, and only the arguments following |
| 1243 | them still there. Feel free to modify \member{parser.rargs}, |
| 1244 | e.g. by consuming more arguments. |
| 1245 | |
| 1246 | \term{parser.largs} |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1247 | the current set of leftover arguments, i.e. arguments that have been |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1248 | processed but have not been consumed as options (or arguments to |
| 1249 | options). Feel free to modify \member{parser.largs} e.g. by adding |
| 1250 | more arguments to it. |
| 1251 | |
| 1252 | \term{parser.values} |
| 1253 | the object where option values are by default stored. This is useful |
| 1254 | because it lets callbacks use the same mechanism as the rest of |
| 1255 | \module{optparse} for storing option values; you don't need to mess |
| 1256 | around with globals or closures. You can also access the value(s) of |
| 1257 | any options already encountered on the command-line. |
| 1258 | \end{definitions} |
| 1259 | |
| 1260 | \term{args} |
| 1261 | is a tuple of arbitrary positional arguments supplied via the |
| 1262 | \var{callback}_args option attribute. |
| 1263 | |
| 1264 | \term{kwargs} |
| 1265 | is a dictionary of arbitrary keyword arguments supplied via |
| 1266 | \var{callback_kwargs}. |
| 1267 | \end{definitions} |
| 1268 | |
| 1269 | Since \var{args} and \var{kwargs} are optional (they are only passed |
| 1270 | if you supply \var{callback_args} and/or \var{callback_kwargs} when |
| 1271 | you define your callback option), the minimal callback function is: |
| 1272 | |
| 1273 | \begin{verbatim} |
| 1274 | def my_callback (option, opt, value, parser): |
| 1275 | pass |
| 1276 | \end{verbatim} |
| 1277 | |
| 1278 | \subsubsection{Error handling\label{optparse-callback-error-handling}} |
| 1279 | |
| 1280 | The callback function should raise \exception{OptionValueError} if |
| 1281 | there are any problems with the option or its |
| 1282 | argument(s). \module{optparse} catches this and terminates the |
| 1283 | program, printing the error message you supply to stderr. Your |
| 1284 | message should be clear, concise, accurate, and mention the option at |
| 1285 | fault. Otherwise, the user will have a hard time figuring out what he |
| 1286 | did wrong. |
| 1287 | |
| 1288 | \subsubsection{Examples\label{optparse-callback-examples}} |
| 1289 | |
| 1290 | Here's an example of a callback option that takes no arguments, and |
| 1291 | simply records that the option was seen: |
| 1292 | |
| 1293 | \begin{verbatim} |
| 1294 | def record_foo_seen (option, opt, value, parser): |
| 1295 | parser.saw_foo = 1 |
| 1296 | |
| 1297 | parser.add_option("--foo", action="callback", callback=record_foo_seen) |
| 1298 | \end{verbatim} |
| 1299 | |
| 1300 | Of course, you could do that with the ``store_true'' action. Here's a |
| 1301 | slightly more interesting example: record the fact that |
| 1302 | \programopt{-a} is seen, but blow up if it comes after \programopt{-b} |
| 1303 | in the command-line. |
| 1304 | |
| 1305 | \begin{verbatim} |
| 1306 | def check_order (option, opt, value, parser): |
| 1307 | if parser.values.b: |
| 1308 | raise OptionValueError("can't use -a after -b") |
| 1309 | parser.values.a = 1 |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1310 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1311 | parser.add_option("-a", action="callback", callback=check_order) |
| 1312 | parser.add_option("-b", action="store_true", dest="b") |
| 1313 | \end{verbatim} |
| 1314 | |
| 1315 | If you want to reuse this callback for several similar options (set a |
| 1316 | flag, but blow up if \programopt{-b} has already been seen), it needs |
| 1317 | a bit of work: the error message and the flag that it sets must be |
| 1318 | generalized. |
| 1319 | |
| 1320 | \begin{verbatim} |
| 1321 | def check_order (option, opt, value, parser): |
| 1322 | if parser.values.b: |
| 1323 | raise OptionValueError("can't use %s after -b" % opt) |
| 1324 | setattr(parser.values, option.dest, 1) |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1325 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1326 | parser.add_option("-a", action="callback", callback=check_order, dest='a') |
| 1327 | parser.add_option("-b", action="store_true", dest="b") |
| 1328 | parser.add_option("-c", action="callback", callback=check_order, dest='c') |
| 1329 | \end{verbatim} |
| 1330 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1331 | 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] | 1332 | to checking the values of already-defined options. For example, if |
| 1333 | you have options that should not be called when the moon is full, all |
| 1334 | you have to do is this: |
| 1335 | |
| 1336 | \begin{verbatim} |
| 1337 | def check_moon (option, opt, value, parser): |
| 1338 | if is_full_moon(): |
| 1339 | raise OptionValueError("%s option invalid when moon full" % opt) |
| 1340 | setattr(parser.values, option.dest, 1) |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1341 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1342 | parser.add_option("--foo", |
| 1343 | action="callback", callback=check_moon, dest="foo") |
| 1344 | \end{verbatim} |
| 1345 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1346 | (The definition of \code{is_full_moon()} is left as an exercise for the |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1347 | reader.) |
| 1348 | |
| 1349 | \strong{Fixed arguments} |
| 1350 | |
| 1351 | Things get slightly more interesting when you define callback options |
| 1352 | that take a fixed number of arguments. Specifying that a callback |
| 1353 | option takes arguments is similar to defining a ``store'' or |
| 1354 | ``append'' option: if you define \var{type}, then the option takes one |
| 1355 | argument that must be convertible to that type; if you further define |
| 1356 | \var{nargs}, then the option takes that many arguments. |
| 1357 | |
| 1358 | Here's an example that just emulates the standard ``store'' action: |
| 1359 | |
| 1360 | \begin{verbatim} |
| 1361 | def store_value (option, opt, value, parser): |
| 1362 | setattr(parser.values, option.dest, value) |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1363 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1364 | parser.add_option("--foo", |
| 1365 | action="callback", callback=store_value, |
| 1366 | type="int", nargs=3, dest="foo") |
| 1367 | \end{verbatim} |
| 1368 | |
| 1369 | Note that \module{optparse} takes care of consuming 3 arguments and |
| 1370 | converting them to integers for you; all you have to do is store them. |
| 1371 | (Or whatever: obviously you don't need a callback for this example. |
| 1372 | Use your imagination!) |
| 1373 | |
| 1374 | \strong{Variable arguments} |
| 1375 | |
| 1376 | Things get hairy when you want an option to take a variable number of |
| 1377 | arguments. For this case, you have to write a callback; |
| 1378 | \module{optparse} doesn't provide any built-in capabilities for it. |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1379 | You have to deal with the full-blown syntax for conventional \UNIX{} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1380 | command-line parsing. (Previously, \module{optparse} took care of |
| 1381 | this for you, but I got it wrong. It was fixed at the cost of making |
| 1382 | this kind of callback more complex.) In particular, callbacks have to |
| 1383 | worry about bare \longprogramopt{} and \programopt{-} arguments; the |
| 1384 | convention is: |
| 1385 | |
| 1386 | \begin{itemize} |
| 1387 | \item bare \longprogramopt{}, if not the argument to some option, |
| 1388 | causes command-line processing to halt and the \longprogramopt{} |
| 1389 | itself is lost. |
| 1390 | |
| 1391 | \item bare \programopt{-} similarly causes command-line processing to |
| 1392 | halt, but the \programopt{-} itself is kept. |
| 1393 | |
| 1394 | \item either \longprogramopt{} or \programopt{-} can be option |
| 1395 | arguments. |
| 1396 | \end{itemize} |
| 1397 | |
| 1398 | If you want an option that takes a variable number of arguments, there |
| 1399 | are several subtle, tricky issues to worry about. The exact |
| 1400 | implementation you choose will be based on which trade-offs you're |
| 1401 | willing to make for your application (which is why \module{optparse} |
| 1402 | doesn't support this sort of thing directly). |
| 1403 | |
| 1404 | Nevertheless, here's a stab at a callback for an option with variable |
| 1405 | arguments: |
| 1406 | |
| 1407 | \begin{verbatim} |
| 1408 | def varargs (option, opt, value, parser): |
| 1409 | assert value is None |
| 1410 | done = 0 |
| 1411 | value = [] |
| 1412 | rargs = parser.rargs |
| 1413 | while rargs: |
| 1414 | arg = rargs[0] |
| 1415 | |
| 1416 | # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f", |
| 1417 | # etc. Note that this also stops on "-3" or "-3.0", so if |
| 1418 | # your option takes numeric values, you will need to handle |
| 1419 | # this. |
| 1420 | if ((arg[:2] == "--" and len(arg) > 2) or |
| 1421 | (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): |
| 1422 | break |
| 1423 | else: |
| 1424 | value.append(arg) |
| 1425 | del rargs[0] |
| 1426 | |
| 1427 | setattr(parser.values, option.dest, value) |
| 1428 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1429 | ... |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1430 | parser.add_option("-c", "--callback", |
| 1431 | action="callback", callback=varargs) |
| 1432 | \end{verbatim} |
| 1433 | |
| 1434 | The main weakness with this particular implementation is that negative |
| 1435 | numbers in the arguments following \programopt{-c} will be interpreted |
| 1436 | as further options, rather than as arguments to \programopt{-c}. |
| 1437 | Fixing this is left as an exercise for the reader. |
| 1438 | |
| 1439 | \subsection{Extending \module{optparse}\label{optparse-extending}} |
| 1440 | |
| 1441 | Since the two major controlling factors in how \module{optparse} |
| 1442 | interprets command-line options are the action and type of each |
| 1443 | option, the most likely direction of extension is to add new actions |
| 1444 | and new types. |
| 1445 | |
| 1446 | Also, the examples section includes several demonstrations of |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1447 | extending \module{optparse} in different ways: e.g. a case-insensitive |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1448 | option parser, or two kinds of option parsers that implement |
| 1449 | ``required options''. |
| 1450 | |
| 1451 | \subsubsection{Adding new types\label{optparse-adding-types}} |
| 1452 | |
| 1453 | To add new types, you need to define your own subclass of |
| 1454 | \module{optparse}'s \class{Option} class. This class has a couple of |
| 1455 | attributes that define \module{optparse}'s types: \member{TYPES} and |
| 1456 | \member{TYPE_CHECKER}. |
| 1457 | |
| 1458 | \member{TYPES} is a tuple of type names; in your subclass, simply |
| 1459 | define a new tuple \member{TYPES} that builds on the standard one. |
| 1460 | |
| 1461 | \member{TYPE_CHECKER} is a dictionary mapping type names to |
| 1462 | type-checking functions. A type-checking function has the following |
| 1463 | signature: |
| 1464 | |
| 1465 | \begin{verbatim} |
| 1466 | def check_foo (option : Option, opt : string, value : string) |
| 1467 | -> foo |
| 1468 | \end{verbatim} |
| 1469 | |
| 1470 | You can name it whatever you like, and make it return any type you |
| 1471 | like. The value returned by a type-checking function will wind up in |
| 1472 | the \class{OptionValues} instance returned by |
| 1473 | \method{OptionParser.parse_args()}, or be passed to callbacks as the |
| 1474 | \var{value} parameter. |
| 1475 | |
| 1476 | Your type-checking function should raise \exception{OptionValueError} |
| 1477 | if it encounters any problems. \exception{OptionValueError} takes a |
| 1478 | single string argument, which is passed as-is to |
| 1479 | \class{OptionParser}'s \method{error()} method, which in turn prepends |
| 1480 | the program name and the string ``error:'' and prints everything to |
| 1481 | stderr before terminating the process. |
| 1482 | |
| 1483 | Here's a silly example that demonstrates adding a ``complex'' option |
| 1484 | type to parse Python-style complex numbers on the command line. (This |
| 1485 | is even sillier than it used to be, because \module{optparse} 1.3 adds |
| 1486 | built-in support for complex numbers [purely for completeness], but |
| 1487 | never mind.) |
| 1488 | |
| 1489 | First, the necessary imports: |
| 1490 | |
| 1491 | \begin{verbatim} |
| 1492 | from copy import copy |
| 1493 | from optparse import Option, OptionValueError |
| 1494 | \end{verbatim} |
| 1495 | |
| 1496 | You need to define your type-checker first, since it's referred to |
| 1497 | later (in the \member{TYPE_CHECKER} class attribute of your |
| 1498 | \class{Option} subclass): |
| 1499 | |
| 1500 | \begin{verbatim} |
| 1501 | def check_complex (option, opt, value): |
| 1502 | try: |
| 1503 | return complex(value) |
| 1504 | except ValueError: |
| 1505 | raise OptionValueError( |
| 1506 | "option %s: invalid complex value: %r" % (opt, value)) |
| 1507 | \end{verbatim} |
| 1508 | |
| 1509 | Finally, the \class{Option} subclass: |
| 1510 | |
| 1511 | \begin{verbatim} |
| 1512 | class MyOption (Option): |
| 1513 | TYPES = Option.TYPES + ("complex",) |
| 1514 | TYPE_CHECKER = copy(Option.TYPE_CHECKER) |
| 1515 | TYPE_CHECKER["complex"] = check_complex |
| 1516 | \end{verbatim} |
| 1517 | |
| 1518 | (If we didn't make a \function{copy()} of |
| 1519 | \member{Option.TYPE_CHECKER}, we would end up modifying the |
| 1520 | \member{TYPE_CHECKER} attribute of \module{optparse}'s Option class. |
| 1521 | This being Python, nothing stops you from doing that except good |
| 1522 | manners and common sense.) |
| 1523 | |
| 1524 | That's it! Now you can write a script that uses the new option type |
| 1525 | just like any other \module{optparse}-based script, except you have to |
| 1526 | instruct your \class{OptionParser} to use \class{MyOption} instead of |
| 1527 | \class{Option}: |
| 1528 | |
| 1529 | \begin{verbatim} |
| 1530 | parser = OptionParser(option_class=MyOption) |
| 1531 | parser.add_option("-c", action="store", type="complex", dest="c") |
| 1532 | \end{verbatim} |
| 1533 | |
| 1534 | Alternately, you can build your own option list and pass it to |
| 1535 | \class{OptionParser}; if you don't use \method{add_option()} in the |
| 1536 | above way, you don't need to tell \class{OptionParser} which option |
| 1537 | class to use: |
| 1538 | |
| 1539 | \begin{verbatim} |
| 1540 | option_list = [MyOption("-c", action="store", type="complex", dest="c")] |
| 1541 | parser = OptionParser(option_list=option_list) |
| 1542 | \end{verbatim} |
| 1543 | |
| 1544 | \subsubsection{Adding new actions\label{optparse-adding-actions}} |
| 1545 | |
| 1546 | Adding new actions is a bit trickier, because you have to understand |
| 1547 | that \module{optparse} has a couple of classifications for actions: |
| 1548 | |
| 1549 | \begin{definitions} |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1550 | \term{``store'' actions} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1551 | actions that result in \module{optparse} storing a value to an attribute |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1552 | of the OptionValues instance; these options require a \var{dest} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1553 | attribute to be supplied to the Option constructor |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1554 | \term{``typed'' actions} |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1555 | actions that take a value from the command line and expect it to be |
| 1556 | of a certain type; or rather, a string that can be converted to a |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1557 | certain type. These options require a \var{type} attribute to the |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1558 | Option constructor. |
| 1559 | \end{definitions} |
| 1560 | |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1561 | Some default ``store'' actions are \var{store}, \var{store_const}, |
| 1562 | \var{append}, and \var{count}. The default ``typed'' actions are |
| 1563 | \var{store}, \var{append}, and \var{callback}. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1564 | |
| 1565 | When you add an action, you need to decide if it's a ``store'' action, |
| 1566 | a ``typed'', neither, or both. Three class attributes of |
| 1567 | \class{Option} (or your \class{Option} subclass) control this: |
| 1568 | |
| 1569 | \begin{memberdesc}{ACTIONS} |
| 1570 | All actions must be listed as strings in ACTIONS. |
| 1571 | \end{memberdesc} |
| 1572 | \begin{memberdesc}{STORE_ACTIONS} |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1573 | ``store'' actions are additionally listed here. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1574 | \end{memberdesc} |
| 1575 | \begin{memberdesc}{TYPED_ACTIONS} |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1576 | ``typed'' actions are additionally listed here. |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1577 | \end{memberdesc} |
| 1578 | |
| 1579 | In order to actually implement your new action, you must override |
| 1580 | \class{Option}'s \method{take_action()} method and add a case that |
| 1581 | recognizes your action. |
| 1582 | |
| 1583 | For example, let's add an ``extend'' action. This is similar to the |
| 1584 | standard ``append'' action, but instead of taking a single value from |
| 1585 | the command-line and appending it to an existing list, ``extend'' will |
| 1586 | take multiple values in a single comma-delimited string, and extend an |
| 1587 | existing list with them. That is, if \longprogramopt{names} is an |
| 1588 | ``extend'' option of type string, the command line: |
| 1589 | |
| 1590 | \begin{verbatim} |
| 1591 | --names=foo,bar --names blah --names ding,dong |
| 1592 | \end{verbatim} |
| 1593 | |
| 1594 | would result in a list: |
| 1595 | |
| 1596 | \begin{verbatim} |
| 1597 | ["foo", "bar", "blah", "ding", "dong"] |
| 1598 | \end{verbatim} |
| 1599 | |
| 1600 | Again we define a subclass of \class{Option}: |
| 1601 | |
| 1602 | \begin{verbatim} |
| 1603 | class MyOption (Option): |
| 1604 | |
| 1605 | ACTIONS = Option.ACTIONS + ("extend",) |
| 1606 | STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) |
| 1607 | TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) |
| 1608 | |
| 1609 | def take_action (self, action, dest, opt, value, values, parser): |
| 1610 | if action == "extend": |
| 1611 | lvalue = value.split(",") |
| 1612 | values.ensure_value(dest, []).extend(lvalue) |
| 1613 | else: |
| 1614 | Option.take_action( |
| 1615 | self, action, dest, opt, value, values, parser) |
| 1616 | \end{verbatim} |
| 1617 | |
| 1618 | Features of note: |
| 1619 | |
| 1620 | \begin{itemize} |
| 1621 | \item ``extend'' both expects a value on the command-line and stores that |
| 1622 | value somewhere, so it goes in both \member{STORE_ACTIONS} and |
| 1623 | \member{TYPED_ACTIONS}. |
| 1624 | |
| 1625 | \item \method{MyOption.take_action()} implements just this one new |
| 1626 | action, and passes control back to \method{Option.take_action()} for |
| 1627 | the standard \module{optparse} actions. |
| 1628 | |
| 1629 | \item \var{values} is an instance of the \class{Values} class, which |
| 1630 | provides the very useful \method{ensure_value()} |
| 1631 | method. \method{ensure_value()} is essentially \function{getattr()} |
| 1632 | with a safety valve; it is called as: |
| 1633 | |
| 1634 | \begin{verbatim} |
| 1635 | values.ensure_value(attr, value) |
| 1636 | \end{verbatim} |
| 1637 | \end{itemize} |
| 1638 | |
| 1639 | If the \member{attr} attribute of \var{values} doesn't exist or is |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1640 | \code{None}, then \method{ensure_value()} first sets it to \var{value}, and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1641 | then returns \var{value}. This is very handy for actions like |
| 1642 | ``extend'', ``append'', and ``count'', all of which accumulate data in |
| 1643 | a variable and expect that variable to be of a certain type (a list |
| 1644 | for the first two, an integer for the latter). Using |
| 1645 | \method{ensure_value()} means that scripts using your action don't |
| 1646 | have to worry about setting a default value for the option |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1647 | destinations in question; they can just leave the default as \code{None} and |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1648 | \method{ensure_value()} will take care of getting it right when it's |
| 1649 | needed. |
| 1650 | |
| 1651 | \subsubsection{Other reasons to extend \module{optparse}\label{optparse-extending-other-reasons}} |
| 1652 | |
| 1653 | Adding new types and new actions are the big, obvious reasons why you |
| 1654 | might want to extend \module{optparse}. I can think of at least two |
| 1655 | other areas to play with. |
| 1656 | |
| 1657 | First, the simple one: \class{OptionParser} tries to be helpful by |
Greg Ward | d723128 | 2003-05-03 21:22:58 +0000 | [diff] [blame] | 1658 | calling \function{sys.exit()} when appropriate, i.e. when there's an |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1659 | error on the command-line or when the user requests help. In the |
| 1660 | former case, the traditional course of letting the script crash with a |
| 1661 | traceback is unacceptable; it will make users think there's a bug in |
| 1662 | your script when they make a command-line error. In the latter case, |
| 1663 | there's generally not much point in carrying on after printing a help |
| 1664 | message. |
| 1665 | |
| 1666 | If this behaviour bothers you, it shouldn't be too hard to ``fix'' it. |
| 1667 | You'll have to |
| 1668 | |
| 1669 | \begin{enumerate} |
| 1670 | \item subclass OptionParser and override the error() method |
Greg Ward | bf8f1b5 | 2003-05-03 19:41:45 +0000 | [diff] [blame] | 1671 | \item subclass Option and override the take_action() method---you'll |
| 1672 | need to provide your own handling of the ``help'' action that |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1673 | doesn't call sys.exit() |
| 1674 | \end{enumerate} |
| 1675 | |
| 1676 | The second, much more complex, possibility is to override the |
| 1677 | command-line syntax implemented by \module{optparse}. In this case, |
| 1678 | you'd leave the whole machinery of option actions and types alone, but |
Fred Drake | 853276e | 2003-07-16 17:58:38 +0000 | [diff] [blame] | 1679 | rewrite the code that processes \code{sys.argv}. You'll need to |
Neal Norwitz | 488609e | 2003-01-06 16:51:37 +0000 | [diff] [blame] | 1680 | subclass \class{OptionParser} in any case; depending on how radical a |
| 1681 | rewrite you want, you'll probably need to override one or all of |
| 1682 | \method{parse_args()}, \method{_process_long_opt()}, and |
| 1683 | \method{_process_short_opts()}. |
| 1684 | |
| 1685 | Both of these are left as an exercise for the reader. I have not |
| 1686 | tried to implement either myself, since I'm quite happy with |
| 1687 | \module{optparse}'s default behaviour (naturally). |
| 1688 | |
| 1689 | Happy hacking, and don't forget: Use the Source, Luke. |
| 1690 | |
| 1691 | \subsubsection{Examples\label{optparse-extending-examples}} |
| 1692 | |
| 1693 | Here are a few examples of extending the \module{optparse} module. |
| 1694 | |
| 1695 | First, let's change the option-parsing to be case-insensitive: |
| 1696 | |
| 1697 | \verbatiminput{caseless.py} |
| 1698 | |
| 1699 | And two ways of implementing ``required options'' with |
| 1700 | \module{optparse}. |
| 1701 | |
| 1702 | Version 1: Add a method to \class{OptionParser} which applications |
| 1703 | must call after parsing arguments: |
| 1704 | |
| 1705 | \verbatiminput{required_1.py} |
| 1706 | |
| 1707 | Version 2: Extend \class{Option} and add a \member{required} |
| 1708 | attribute; extend \class{OptionParser} to ensure that required options |
| 1709 | are present after parsing: |
| 1710 | |
Fred Drake | cf6d74a | 2003-04-18 15:50:13 +0000 | [diff] [blame] | 1711 | \verbatiminput{required_2.py} |