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