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