Changeset 391 for python/trunk/Doc/library/optparse.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/optparse.rst
r2 r391 1 :mod:`optparse` --- More powerful command line option parser2 =================================================== =========1 :mod:`optparse` --- Parser for command line options 2 =================================================== 3 3 4 4 .. module:: optparse 5 :synopsis: More convenient, flexible, and powerful command-line parsing library. 5 :synopsis: Command-line option parsing library. 6 :deprecated: 6 7 .. moduleauthor:: Greg Ward <gward@python.net> 7 8 .. sectionauthor:: Greg Ward <gward@python.net> 8 9 9 10 .. versionadded:: 2.3 10 11 11 .. sectionauthor:: Greg Ward <gward@python.net> 12 12 .. deprecated:: 2.7 13 The :mod:`optparse` module is deprecated and will not be developed further; 14 development will continue with the :mod:`argparse` module. 15 16 **Source code:** :source:`Lib/optparse.py` 17 18 -------------- 13 19 14 20 :mod:`optparse` is a more convenient, flexible, and powerful library for parsing … … 60 66 .. code-block:: text 61 67 62 usage: <yourscript> [options]63 64 options:68 Usage: <yourscript> [options] 69 70 Options: 65 71 -h, --help show this help message and exit 66 72 -f FILE, --file=FILE write report to FILE … … 103 109 execution of a program. There are many different syntaxes for options; the 104 110 traditional Unix syntax is a hyphen ("-") followed by a single letter, 105 e.g. `` "-x"`` or ``"-F"``. Also, traditional Unix syntax allows multiple106 options to be merged into a single argument, e.g. ``"-x -F"`` is equivalent107 to `` "-xF"``. The GNU project introduced ``"--"`` followed by a series of108 hyphen-separated words, e.g. ``"--file"`` or ``"--dry-run"``. These are the111 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 109 115 only two option syntaxes provided by :mod:`optparse`. 110 116 111 117 Some other option syntaxes that the world has seen include: 112 118 113 * a hyphen followed by a few letters, e.g. `` "-pf"`` (this is *not* the same119 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same 114 120 as multiple options merged into a single argument) 115 121 116 * a hyphen followed by a whole word, e.g. `` "-file"`` (this is technically122 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically 117 123 equivalent to the previous syntax, but they aren't usually seen in the same 118 124 program) 119 125 120 126 * a plus sign followed by a single letter, or a few letters, or a word, e.g. 121 `` "+f"``, ``"+rgb"``122 123 * a slash followed by a letter, or a few letters, or a word, e.g. `` "/f"``,124 `` "/file"``127 ``+f``, ``+rgb`` 128 129 * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``, 130 ``/file`` 125 131 126 132 These option syntaxes are not supported by :mod:`optparse`, and they never … … 150 156 people want an "optional option arguments" feature, meaning that some options 151 157 will take an argument if they see it, and won't if they don't. This is 152 somewhat controversial, because it makes parsing ambiguous: if `` "-a"`` takes153 an optional argument and `` "-b"`` is another option entirely, how do we154 interpret `` "-ab"``? Because of this ambiguity, :mod:`optparse` does not158 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 155 161 support this feature. 156 162 … … 164 170 "required option" is self-contradictory in English. :mod:`optparse` doesn't 165 171 prevent you from implementing required options, but doesn't give you much 166 help at it either. See ``examples/required_1.py`` and 167 ``examples/required_2.py`` in the :mod:`optparse` source distribution for two 168 ways to implement required options with :mod:`optparse`. 172 help at it either. 169 173 170 174 For example, consider this hypothetical command-line:: 171 175 172 prog -v --report /tmp/report.txt foo bar173 174 `` "-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`175 takes one argument, `` "/tmp/report.txt"`` is an option argument. ``"foo"`` and176 `` "bar"`` are positional arguments.176 prog -v --report report.txt foo bar 177 178 ``-v`` and ``--report`` are both options. Assuming that ``--report`` 179 takes one argument, ``report.txt`` is an option argument. ``foo`` and 180 ``bar`` are positional arguments. 177 181 178 182 … … 259 263 attr=value, ...) 260 264 261 Each option has one or more option strings, such as `` "-f"`` or ``"--file"``,265 Each option has one or more option strings, such as ``-f`` or ``--file``, 262 266 and several option attributes that tell :mod:`optparse` what to expect and what 263 267 to do when it encounters that option on the command line. … … 272 276 string overall. 273 277 274 The option strings passed to :meth:`add_option` are effectively labels for the 278 The option strings passed to :meth:`OptionParser.add_option` are effectively 279 labels for the 275 280 option defined by that call. For brevity, we will frequently refer to 276 281 *encountering an option* on the command line; in reality, :mod:`optparse` … … 288 293 289 294 * ``options``, an object containing values for all of your options---e.g. if 290 `` "--file"`` takes a single string argument, then ``options.file`` will be the295 ``--file`` takes a single string argument, then ``options.file`` will be the 291 296 filename supplied by the user, or ``None`` if the user did not supply that 292 297 option … … 334 339 (options, args) = parser.parse_args(args) 335 340 336 When :mod:`optparse` sees the option string `` "-f"``, it consumes the next337 argument, `` "foo.txt"``, and stores it in ``options.filename``. So, after this341 When :mod:`optparse` sees the option string ``-f``, it consumes the next 342 argument, ``foo.txt``, and stores it in ``options.filename``. So, after this 338 343 call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``. 339 344 … … 347 352 348 353 Let's parse another fake command-line. This time, we'll jam the option argument 349 right up against the option: since `` "-n42"`` (one argument) is equivalent to350 `` "-n 42"`` (two arguments), the code ::354 right up against the option: since ``-n42`` (one argument) is equivalent to 355 ``-n 42`` (two arguments), the code :: 351 356 352 357 (options, args) = parser.parse_args(["-n42"]) 353 358 print options.num 354 359 355 will print `` "42"``.360 will print ``42``. 356 361 357 362 If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with … … 363 368 If you don't supply a destination, :mod:`optparse` figures out a sensible 364 369 default from the option strings: if the first long option string is 365 `` "--foo-bar"``, then the default destination is ``foo_bar``. If there are no370 ``--foo-bar``, then the default destination is ``foo_bar``. If there are no 366 371 long option strings, :mod:`optparse` looks at the first short option string: the 367 default destination for `` "-f"`` is ``f``.372 default destination for ``-f`` is ``f``. 368 373 369 374 :mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding … … 379 384 ---are quite common. :mod:`optparse` supports them with two separate actions, 380 385 ``store_true`` and ``store_false``. For example, you might have a ``verbose`` 381 flag that is turned on with `` "-v"`` and off with ``"-q"``::386 flag that is turned on with ``-v`` and off with ``-q``:: 382 387 383 388 parser.add_option("-v", action="store_true", dest="verbose") … … 388 393 see below.) 389 394 390 When :mod:`optparse` encounters `` "-v"`` on the command line, it sets391 ``options.verbose`` to ``True``; when it encounters `` "-q"``,395 When :mod:`optparse` encounters ``-v`` on the command line, it sets 396 ``options.verbose`` to ``True``; when it encounters ``-q``, 392 397 ``options.verbose`` is set to ``False``. 393 398 … … 429 434 430 435 First, consider the verbose/quiet example. If we want :mod:`optparse` to set 431 ``verbose`` to ``True`` unless `` "-q"`` is seen, then we can do this::436 ``verbose`` to ``True`` unless ``-q`` is seen, then we can do this:: 432 437 433 438 parser.add_option("-v", action="store_true", dest="verbose", default=True) … … 487 492 "or expert [default: %default]") 488 493 489 If :mod:`optparse` encounters either `` "-h"`` or ``"--help"`` on the494 If :mod:`optparse` encounters either ``-h`` or ``--help`` on the 490 495 command-line, or if you just call :meth:`parser.print_help`, it prints the 491 496 following to standard output: … … 493 498 .. code-block:: text 494 499 495 usage: <yourscript> [options] arg1 arg2496 497 options:500 Usage: <yourscript> [options] arg1 arg2 501 502 Options: 498 503 -h, --help show this help message and exit 499 504 -v, --verbose make lots of noise [default] … … 514 519 usage = "usage: %prog [options] arg1 arg2" 515 520 516 :mod:`optparse` expands `` "%prog"`` in the usage string to the name of the521 :mod:`optparse` expands ``%prog`` in the usage string to the name of the 517 522 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string 518 523 is then printed before the detailed option help. 519 524 520 525 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible 521 default: ``" usage: %prog [options]"``, which is fine if your script doesn't526 default: ``"Usage: %prog [options]"``, which is fine if your script doesn't 522 527 take any positional arguments. 523 528 … … 532 537 533 538 Here, "MODE" is called the meta-variable: it stands for the argument that the 534 user is expected to supply to :option:`-m`/:option:`--mode`. By default,539 user is expected to supply to ``-m``/``--mode``. By default, 535 540 :mod:`optparse` converts the destination variable name to uppercase and uses 536 541 that for the meta-variable. Sometimes, that's not what you want---for 537 example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,542 example, the ``--filename`` option explicitly sets ``metavar="FILE"``, 538 543 resulting in this automatically-generated option description:: 539 544 … … 541 546 542 547 This is important for more than just saving space, though: the manually 543 written help text uses the meta-variable "FILE"to clue the user in that544 there's a connection between the semi-formal syntax "-f FILE"and the informal548 written help text uses the meta-variable ``FILE`` to clue the user in that 549 there's a connection between the semi-formal syntax ``-f FILE`` and the informal 545 550 semantic description "write output to FILE". This is a simple but effective 546 551 way to make your help text a lot clearer and more useful for end users. … … 552 557 ``None``), ``%default`` expands to ``none``. 553 558 559 Grouping Options 560 ++++++++++++++++ 561 554 562 When dealing with many options, it is convenient to group these options for 555 563 better help output. An :class:`OptionParser` can contain several option groups, 556 564 each of which can contain several options. 557 565 558 Continuing with the parser defined above, adding an :class:`OptionGroup` to a 559 parser is easy:: 566 An 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 insterted 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 579 an option to the group. 580 581 Once 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 584 Continuing with the parser defined in the previous section, adding an 585 :class:`OptionGroup` to a parser is easy:: 560 586 561 587 group = OptionGroup(parser, "Dangerous Options", … … 569 595 .. code-block:: text 570 596 571 usage: [options] arg1 arg2 572 573 options: 574 -h, --help show this help message and exit 575 -v, --verbose make lots of noise [default] 576 -q, --quiet be vewwy quiet (I'm hunting wabbits) 577 -fFILE, --file=FILE write output to FILE 578 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate' 579 [default], 'expert' 580 581 Dangerous Options: 582 Caution: use of these options is at your own risk. It is believed that 583 some of them bite. 584 -g Group option. 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 614 A bit more complete example might involve using more than one group: still 615 extending 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 631 that 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 657 Another interesting method, in particular when working programmatically with 658 option 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``. 585 665 586 666 .. _optparse-printing-version-string: … … 595 675 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0") 596 676 597 `` "%prog"`` is expanded just like it is in ``usage``. Apart from that,677 ``%prog`` is expanded just like it is in ``usage``. Apart from that, 598 678 ``version`` can contain anything you like. When you supply it, :mod:`optparse` 599 automatically adds a `` "--version"`` option to your parser. If it encounters679 automatically adds a ``--version`` option to your parser. If it encounters 600 680 this option on the command line, it expands your ``version`` string (by 601 replacing `` "%prog"``), prints it to stdout, and exits.681 replacing ``%prog``), prints it to stdout, and exits. 602 682 603 683 For example, if your script is called ``/usr/bin/foo``:: … … 612 692 Print the version message for the current program (``self.version``) to 613 693 *file* (default stdout). As with :meth:`print_usage`, any occurrence 614 of `` "%prog"`` in ``self.version`` is replaced with the name of the current694 of ``%prog`` in ``self.version`` is replaced with the name of the current 615 695 program. Does nothing if ``self.version`` is empty or undefined. 616 696 … … 635 715 Handling user errors is much more important, since they are guaranteed to happen 636 716 no matter how stable your code is. :mod:`optparse` can automatically detect 637 some user errors, such as bad option arguments (passing `` "-n 4x"`` where638 :option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end639 of the command line, where :option:`-n` takes an argument of any type). Also,717 some user errors, such as bad option arguments (passing ``-n 4x`` where 718 ``-n`` takes an integer argument), missing arguments (``-n`` at the end 719 of the command line, where ``-n`` takes an argument of any type). Also, 640 720 you can call :func:`OptionParser.error` to signal an application-defined error 641 721 condition:: … … 650 730 error status 2. 651 731 652 Consider the first example above, where the user passes `` "4x"`` to an option732 Consider the first example above, where the user passes ``4x`` to an option 653 733 that takes an integer:: 654 734 655 735 $ /usr/bin/foo -n 4x 656 usage: foo [options]736 Usage: foo [options] 657 737 658 738 foo: error: option -n: invalid integer value: '4x' … … 661 741 662 742 $ /usr/bin/foo -n 663 usage: foo [options]743 Usage: foo [options] 664 744 665 745 foo: error: -n option requires an argument … … 743 823 A version string to print when the user supplies a version option. If you 744 824 supply a true value for ``version``, :mod:`optparse` automatically adds a 745 version option with the single option string `` "--version"``. The746 substring `` "%prog"`` is expanded the same as for ``usage``.825 version option with the single option string ``--version``. The 826 substring ``%prog`` is expanded the same as for ``usage``. 747 827 748 828 ``conflict_handler`` (default: ``"error"``) … … 763 843 764 844 ``add_help_option`` (default: ``True``) 765 If true, :mod:`optparse` will add a help option (with option strings `` "-h"``766 and `` "--help"``) to the parser.845 If true, :mod:`optparse` will add a help option (with option strings ``-h`` 846 and ``--help``) to the parser. 767 847 768 848 ``prog`` 769 The string to use when expanding `` "%prog"`` in ``usage`` and ``version``849 The string to use when expanding ``%prog`` in ``usage`` and ``version`` 770 850 instead of ``os.path.basename(sys.argv[0])``. 771 851 772 852 ``epilog`` (default: ``None``) 853 A paragraph of help text to print after the option help. 773 854 774 855 .. _optparse-populating-parser: … … 810 891 811 892 Each Option instance represents a set of synonymous command-line option strings, 812 e.g. :option:`-f` and :option:`--file`. You can specify any number of short or893 e.g. ``-f`` and ``--file``. You can specify any number of short or 813 894 long option strings, but you must specify at least one overall option string. 814 895 … … 816 897 :meth:`add_option` method of :class:`OptionParser`. 817 898 818 .. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...) 899 .. method:: OptionParser.add_option(option) 900 OptionParser.add_option(*opt_str, attr=value, ...) 819 901 820 902 To define an option with only a short option string:: … … 973 1055 974 1056 Help text to print for this option when listing all available options after 975 the user supplies a :attr:`~Option.help` option (such as `` "--help"``). If1057 the user supplies a :attr:`~Option.help` option (such as ``--help``). If 976 1058 no help text is supplied, the option will be listed without help text. To 977 1059 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`. … … 1011 1093 1012 1094 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination 1013 from the first long option string (e.g., `` "--foo-bar"`` implies1095 from the first long option string (e.g., ``--foo-bar`` implies 1014 1096 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a 1015 destination from the first short option string (e.g., `` "-f"`` implies ``f``).1097 destination from the first short option string (e.g., ``-f`` implies ``f``). 1016 1098 1017 1099 Example:: … … 1044 1126 action="store_const", const=2, dest="verbose") 1045 1127 1046 If `` "--noisy"`` is seen, :mod:`optparse` will set ::1128 If ``--noisy`` is seen, :mod:`optparse` will set :: 1047 1129 1048 1130 options.verbose = 2 … … 1079 1161 parser.add_option("-t", "--tracks", action="append", type="int") 1080 1162 1081 If `` "-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent1163 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent 1082 1164 of:: 1083 1165 … … 1085 1167 options.tracks.append(int("3")) 1086 1168 1087 If, a little later on, `` "--tracks=4"`` is seen, it does::1169 If, a little later on, ``--tracks=4`` is seen, it does:: 1088 1170 1089 1171 options.tracks.append(int("4")) 1172 1173 The ``append`` action calls the ``append`` method on the current value of the 1174 option. This means that any default value specified must have an ``append`` 1175 method. It also means that if the default value is non-empty, the default 1176 elements will be present in the parsed value for the option, with any values 1177 from the command line appended after those default values:: 1178 1179 >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults']) 1180 >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg']) 1181 >>> opts.files 1182 ['~/.mypkg/defaults', 'overrides.mypkg'] 1090 1183 1091 1184 * ``"append_const"`` [required: :attr:`~Option.const`; relevant: … … 1107 1200 parser.add_option("-v", action="count", dest="verbosity") 1108 1201 1109 The first time `` "-v"`` is seen on the command line, :mod:`optparse` does the1202 The first time ``-v`` is seen on the command line, :mod:`optparse` does the 1110 1203 equivalent of:: 1111 1204 … … 1113 1206 options.verbosity += 1 1114 1207 1115 Every subsequent occurrence of `` "-v"`` results in ::1208 Every subsequent occurrence of ``-v`` results in :: 1116 1209 1117 1210 options.verbosity += 1 … … 1156 1249 parser.add_option("--secret", help=SUPPRESS_HELP) 1157 1250 1158 If :mod:`optparse` sees either `` "-h"`` or ``"--help"`` on the command line,1251 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line, 1159 1252 it will print something like the following help message to stdout (assuming 1160 1253 ``sys.argv[0]`` is ``"foo.py"``): … … 1162 1255 .. code-block:: text 1163 1256 1164 usage: foo.py [options]1165 1166 options:1257 Usage: foo.py [options] 1258 1259 Options: 1167 1260 -h, --help Show this help message and exit 1168 1261 -v Be moderately verbose … … 1213 1306 1214 1307 ``"choice"`` options are a subtype of ``"string"`` options. The 1215 :attr:`~Option.choices` `option attribute (a sequence of strings) defines the1308 :attr:`~Option.choices` option attribute (a sequence of strings) defines the 1216 1309 set of allowed option arguments. :func:`optparse.check_choice` compares 1217 1310 user-supplied option arguments against this master list and raises … … 1235 1328 1236 1329 ``values`` 1237 object to store option arguments in (default: a new instance of 1238 :class:`optparse.Values`) 1330 a :class:`optparse.Values` object to store option arguments in (default: a 1331 new instance of :class:`Values`) -- if you give an existing object, the 1332 option defaults will not be initialized on it 1239 1333 1240 1334 and the return values are … … 1269 1363 .. method:: OptionParser.disable_interspersed_args() 1270 1364 1271 Set parsing to stop on the first non-option. For example, if `` "-a"`` and1272 `` "-b"`` are both simple options that take no arguments, :mod:`optparse`1365 Set parsing to stop on the first non-option. For example, if ``-a`` and 1366 ``-b`` are both simple options that take no arguments, :mod:`optparse` 1273 1367 normally accepts this syntax:: 1274 1368 … … 1300 1394 1301 1395 Return true if the OptionParser has an option with option string *opt_str* 1302 (e.g., `` "-q"`` or ``"--verbose"``).1396 (e.g., ``-q`` or ``--verbose``). 1303 1397 1304 1398 .. method:: OptionParser.remove_option(opt_str) … … 1353 1447 1354 1448 At this point, :mod:`optparse` detects that a previously-added option is already 1355 using the `` "-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,1356 it resolves the situation by removing `` "-n"`` from the earlier option's list of1357 option strings. Now `` "--dry-run"`` is the only way for the user to activate1449 using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``, 1450 it resolves the situation by removing ``-n`` from the earlier option's list of 1451 option strings. Now ``--dry-run`` is the only way for the user to activate 1358 1452 that option. If the user asks for help, the help message will reflect that:: 1359 1453 1360 options:1454 Options: 1361 1455 --dry-run do no harm 1362 1456 [...] … … 1371 1465 parser.add_option("--dry-run", ..., help="new dry-run option") 1372 1466 1373 At this point, the original :option:`-n/--dry-run` option is no longer1467 At this point, the original ``-n``/``--dry-run`` option is no longer 1374 1468 accessible, so :mod:`optparse` removes it, leaving this help text:: 1375 1469 1376 options:1470 Options: 1377 1471 [...] 1378 1472 -n, --noisy be noisy … … 1409 1503 1410 1504 Print the usage message for the current program (``self.usage``) to *file* 1411 (default stdout). Any occurrence of the string `` "%prog"`` in ``self.usage``1505 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage`` 1412 1506 is replaced with the name of the current program. Does nothing if 1413 1507 ``self.usage`` is empty or not defined. … … 1473 1567 ``callback`` is a function (or other callable object), so you must have already 1474 1568 defined ``my_callback()`` when you create this callback option. In this simple 1475 case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,1569 case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments, 1476 1570 which usually means that the option takes no arguments---the mere presence of 1477 :option:`-c` on the command-line is all it needs to know. In some1571 ``-c`` on the command-line is all it needs to know. In some 1478 1572 circumstances, though, you might want your callback to consume an arbitrary 1479 1573 number of command-line arguments. This is where writing callbacks gets tricky; … … 1528 1622 is the option string seen on the command-line that's triggering the callback. 1529 1623 (If an abbreviated long option was used, ``opt_str`` will be the full, 1530 canonical option string---e.g. if the user puts `` "--foo"`` on the1531 command-line as an abbreviation for `` "--foobar"``, then ``opt_str`` will be1624 canonical option string---e.g. if the user puts ``--foo`` on the 1625 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be 1532 1626 ``"--foobar"``.) 1533 1627 … … 1604 1698 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1605 1699 1606 Here's a slightly more interesting example: record the fact that `` "-a"`` is1607 seen, but blow up if it comes after `` "-b"`` in the command-line. ::1700 Here's a slightly more interesting example: record the fact that ``-a`` is 1701 seen, but blow up if it comes after ``-b`` in the command-line. :: 1608 1702 1609 1703 def check_order(option, opt_str, value, parser): … … 1622 1716 1623 1717 If you want to re-use this callback for several similar options (set a flag, but 1624 blow up if `` "-b"`` has already been seen), it needs a bit of work: the error1718 blow up if ``-b`` has already been seen), it needs a bit of work: the error 1625 1719 message and the flag that it sets must be generalized. :: 1626 1720 … … 1692 1786 conventional Unix command-line parsing that :mod:`optparse` normally handles for 1693 1787 you. In particular, callbacks should implement the conventional rules for bare 1694 `` "--"`` and ``"-"`` arguments:1695 1696 * either `` "--"`` or ``"-"`` can be option arguments1697 1698 * bare `` "--"`` (if not the argument to some option): halt command-line1699 processing and discard the `` "--"``1700 1701 * bare `` "-"`` (if not the argument to some option): halt command-line1702 processing but keep the `` "-"`` (append it to ``parser.largs``)1788 ``--`` and ``-`` arguments: 1789 1790 * either ``--`` or ``-`` can be option arguments 1791 1792 * bare ``--`` (if not the argument to some option): halt command-line 1793 processing and discard the ``--`` 1794 1795 * bare ``-`` (if not the argument to some option): halt command-line 1796 processing but keep the ``-`` (append it to ``parser.largs``) 1703 1797 1704 1798 If you want an option that takes a variable number of arguments, there are … … 1771 1865 1772 1866 where ``option`` is an :class:`Option` instance, ``opt`` is an option string 1773 (e.g., `` "-f"``), and ``value`` is the string from the command line that must1867 (e.g., ``-f``), and ``value`` is the string from the command line that must 1774 1868 be checked and converted to your desired type. ``check_mytype()`` should 1775 1869 return an object of the hypothetical type ``mytype``. The value returned by … … 1883 1977 and appending it to an existing list, ``"extend"`` will take multiple values in 1884 1978 a single comma-delimited string, and extend an existing list with them. That 1885 is, if `` "--names"`` is an ``"extend"`` option of type ``"string"``, the command1979 is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command 1886 1980 line :: 1887 1981
Note:
See TracChangeset
for help on using the changeset viewer.