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