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