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