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