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