• Home
  • Raw
  • Download

Lines Matching +full:- +full:- +full:option

1 :mod:`optparse` --- Parser for command line options
5 :synopsis: Command-line option parsing library.
17 --------------
20 command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
21 more declarative style of command-line parsing: you create an instance of
31 parser.add_option("-f", "--file", dest="filename",
33 parser.add_option("-q", "--quiet",
40 on the command-line, for example::
42 <yourscript> --file=outfile -q
45 ``options`` object returned by :meth:`parse_args` based on user-supplied
46 command-line values. When :meth:`parse_args` returns from parsing this command
53 <yourscript> -f outfile --quiet
54 <yourscript> --quiet --file outfile
55 <yourscript> -q -foutfile
56 <yourscript> -qfoutfile
60 <yourscript> -h
61 <yourscript> --help
65 .. code-block:: text
70 -h, --help show this help message and exit
71 -f FILE, --file=FILE write report to FILE
72 -q, --quiet don't print status messages to stdout
78 .. _optparse-background:
81 ----------
84 with straightforward, conventional command-line interfaces. To that end, it
85 supports only the most common command-line syntax and semantics conventionally
90 .. _optparse-terminology:
96 a string entered on the command-line, and passed by the shell to ``execl()``
106 option
109 traditional Unix syntax is a hyphen ("-") followed by a single letter,
110 e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple
111 options to be merged into a single argument, e.g. ``-x -F`` is equivalent
112 to ``-xF``. The GNU project introduced ``--`` followed by a series of
113 hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
114 only two option syntaxes provided by :mod:`optparse`.
116 Some other option syntaxes that the world has seen include:
118 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
121 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
131 These option syntaxes are not supported by :mod:`optparse`, and they never
132 will be. This is deliberate: the first three are non-standard on any
134 Windows or certain legacy platforms (e.g. VMS, MS-DOS).
136 option argument
137 an argument that follows an option, is closely associated with that option,
138 and is consumed from the argument list when that option is. With
139 :mod:`optparse`, option arguments may either be in a separate argument from
140 their option:
142 .. code-block:: text
144 -f foo
145 --file foo
149 .. code-block:: text
151 -ffoo
152 --file=foo
154 Typically, a given option either takes an argument or it doesn't. Lots of
155 people want an "optional option arguments" feature, meaning that some options
157 somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
158 an optional argument and ``-b`` is another option entirely, how do we
159 interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
167 required option
168 an option that must be supplied on the command-line; note that the phrase
169 "required option" is self-contradictory in English. :mod:`optparse` doesn't
173 For example, consider this hypothetical command-line::
175 prog -v --report report.txt foo bar
177 ``-v`` and ``--report`` are both options. Assuming that ``--report``
178 takes one argument, ``report.txt`` is an option argument. ``foo`` and
182 .. _optparse-what-options-for:
192 ``dd``\ ---all of which are mutant oddballs that have been rightly criticized
193 for their non-standard syntax and confusing interfaces.)
200 As an example of good command-line interface design, consider the humble ``cp``
207 cp SOURCE ... DEST-DIR
217 .. _optparse-what-positional-arguments-for:
228 user---most people will give up and walk away before they successfully run the
229 program. This applies whether the user interface is a command-line, a
234 required to supply---use sensible defaults whenever possible. Of course, you
237 the "Preferences" dialog of a GUI, or command-line options---the more options
243 .. _optparse-tutorial:
246 --------
250 any :mod:`optparse`\ -based program.
264 Each option has one or more option strings, such as ``-f`` or ``--file``,
265 and several option attributes that tell :mod:`optparse` what to expect and what
266 to do when it encounters that option on the command line.
268 Typically, each option will have one short option string and one long option
271 parser.add_option("-f", "--file", ...)
273 You're free to define as many short option strings and as many long option
274 strings as you like (including zero), as long as there is at least one option
277 The option strings passed to :meth:`OptionParser.add_option` are effectively
279 option defined by that call. For brevity, we will frequently refer to
280 *encountering an option* on the command line; in reality, :mod:`optparse`
281 encounters *option strings* and looks up options from them.
293 * ``options``, an object containing values for all of your options---e.g. if
294 ``--file`` takes a single string argument, then ``options.file`` will be the
296 option
300 This tutorial section only covers the four most important option attributes:
301 :attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
302 (destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
306 .. _optparse-understanding-option-actions:
308 Understanding option actions
311 Actions tell :mod:`optparse` what to do when it encounters an option on the
312 command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
314 :ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
315 a value in some variable---for example, take a string from the command line and
318 If you don't specify an option action, :mod:`optparse` defaults to ``store``.
321 .. _optparse-store-action:
326 The most common option action is ``store``, which tells :mod:`optparse` to take
332 parser.add_option("-f", "--file",
337 args = ["-f", "foo.txt"]
340 When :mod:`optparse` sees the option string ``-f``, it consumes the next
344 Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
345 Here's an option that expects an integer argument::
347 parser.add_option("-n", type="int", dest="num")
349 Note that this option has no long option string, which is perfectly acceptable.
352 Let's parse another fake command-line. This time, we'll jam the option argument
353 right up against the option: since ``-n42`` (one argument) is equivalent to
354 ``-n 42`` (two arguments), the code ::
356 (options, args) = parser.parse_args(["-n42"])
365 parser.add_option("-f", "--file", dest="filename")
368 default from the option strings: if the first long option string is
369 ``--foo-bar``, then the default destination is ``foo_bar``. If there are no
370 long option strings, :mod:`optparse` looks at the first short option string: the
371 default destination for ``-f`` is ``f``.
373 :mod:`optparse` also includes the built-in ``complex`` type. Adding
374 types is covered in section :ref:`optparse-extending-optparse`.
377 .. _optparse-handling-boolean-options:
382 Flag options---set a variable to true or false when a particular option is
383 seen---are quite common. :mod:`optparse` supports them with two separate actions,
385 flag that is turned on with ``-v`` and off with ``-q``::
387 parser.add_option("-v", action="store_true", dest="verbose")
388 parser.add_option("-q", action="store_false", dest="verbose")
392 values---see below.)
394 When :mod:`optparse` encounters ``-v`` on the command line, it sets
395 ``options.verbose`` to ``True``; when it encounters ``-q``,
399 .. _optparse-other-actions:
407 store a constant value, pre-set via :attr:`Option.const`
410 append this option's argument to a list
418 These are covered in section :ref:`optparse-reference-guide`,
419 and section :ref:`optparse-option-callbacks`.
422 .. _optparse-default-values:
428 certain command-line options are seen. What happens if those options are never
435 ``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
437 parser.add_option("-v", action="store_true", dest="verbose", default=True)
438 parser.add_option("-q", action="store_false", dest="verbose")
441 option, and these two options happen to have the same destination, this is
444 parser.add_option("-v", action="store_true", dest="verbose")
445 parser.add_option("-q", action="store_false", dest="verbose", default=True)
449 parser.add_option("-v", action="store_true", dest="verbose", default=False)
450 parser.add_option("-q", action="store_false", dest="verbose", default=True)
462 As before, the last value specified for a given option destination is the one
467 .. _optparse-generating-help:
473 useful for creating user-friendly command-line interfaces. All you have to do
474 is supply a :attr:`~Option.help` value for each option, and optionally a short
476 user-friendly (documented) options::
480 parser.add_option("-v", "--verbose",
483 parser.add_option("-q", "--quiet",
486 parser.add_option("-f", "--filename",
488 parser.add_option("-m", "--mode",
493 If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
494 command-line, or if you just call :meth:`parser.print_help`, it prints the
497 .. code-block:: text
502 -h, --help show this help message and exit
503 -v, --verbose make lots of noise [default]
504 -q, --quiet be vewwy quiet (I'm hunting wabbits)
505 -f FILE, --filename=FILE
507 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
510 (If the help output is triggered by a help option, :mod:`optparse` exits after
522 is then printed before the detailed option help.
528 * every option defines a help string, and doesn't worry about
529 line-wrapping---\ :mod:`optparse` takes care of wrapping lines and making
533 help message, e.g. for the "mode" option::
535 -m MODE, --mode=MODE
537 Here, "MODE" is called the meta-variable: it stands for the argument that the
538 user is expected to supply to ``-m``/``--mode``. By default,
540 that for the meta-variable. Sometimes, that's not what you want---for
541 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
542 resulting in this automatically generated option description::
544 -f FILE, --filename=FILE
547 written help text uses the meta-variable ``FILE`` to clue the user in that
548 there's a connection between the semi-formal syntax ``-f FILE`` and the informal
553 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
554 default value. If an option has no default value (or the default value is
561 better help output. An :class:`OptionParser` can contain several option groups,
564 An option group is obtained using the class :class:`OptionGroup`:
577 an option to the group.
588 group.add_option("-g", action="store_true", help="Group option.")
593 .. code-block:: text
598 -h, --help show this help message and exit
599 -v, --verbose make lots of noise [default]
600 -q, --quiet be vewwy quiet (I'm hunting wabbits)
601 -f FILE, --filename=FILE
603 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
610 -g Group option.
618 group.add_option("-g", action="store_true", help="Group option.")
622 group.add_option("-d", "--debug", action="store_true",
624 group.add_option("-s", "--sql", action="store_true",
626 group.add_option("-e", action="store_true", help="Print every action done")
631 .. code-block:: text
636 -h, --help show this help message and exit
637 -v, --verbose make lots of noise [default]
638 -q, --quiet be vewwy quiet (I'm hunting wabbits)
639 -f FILE, --filename=FILE
641 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
648 -g Group option.
651 -d, --debug Print debug information
652 -s, --sql Print all SQL statements executed
653 -e Print every action done
656 option groups is:
660 Return the :class:`OptionGroup` to which the short or long option
661 string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
664 .. _optparse-printing-version-string:
673 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
677 automatically adds a ``--version`` option to your parser. If it encounters
678 this option on the command line, it expands your ``version`` string (by
683 .. code-block:: shell-session
685 $ /usr/bin/foo --version
703 .. _optparse-how-optparse-handles-errors:
710 calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
711 option attributes, missing option attributes, etc. These are dealt with in the
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,
720 you can call :func:`OptionParser.error` to signal an application-defined error
726 parser.error("options -a and -b are mutually exclusive")
732 Consider the first example above, where the user passes ``4x`` to an option
735 .. code-block:: shell-session
737 $ /usr/bin/foo -n 4x
740 foo: error: option -n: invalid integer value: '4x'
744 .. code-block:: shell-session
746 $ /usr/bin/foo -n
749 foo: error: -n option requires an argument
751 :mod:`optparse`\ -generated error messages take care always to mention the
752 option involved in the error; be sure to do the same when calling
755 If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
760 .. _optparse-putting-it-all-together:
765 Here's what :mod:`optparse`\ -based scripts usually look like::
772 parser.add_option("-f", "--file", dest="filename",
774 parser.add_option("-v", "--verbose",
776 parser.add_option("-q", "--quiet",
790 .. _optparse-reference-guide:
793 ---------------
796 .. _optparse-creating-parser:
811 help option. When :mod:`optparse` prints the usage string, it expands
817 A list of Option objects to populate the parser with. The options in
823 ``option_class`` (default: optparse.Option)
827 A version string to print when the user supplies a version option. If you
829 version option with the single option string ``--version``. The
833 Specifies what to do when options with conflicting option strings are
835 :ref:`optparse-conflicts-between-options`.
849 If true, :mod:`optparse` will add a help option (with option strings ``-h``
850 and ``--help``) to the parser.
857 A paragraph of help text to print after the option help.
859 .. _optparse-populating-parser:
866 :ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
868 * pass it an Option instance (as returned by :func:`make_option`)
871 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
872 will create the Option instance for you
874 The other alternative is to pass a list of pre-constructed Option instances to
878 make_option("-f", "--filename",
880 make_option("-q", "--quiet",
885 (:func:`make_option` is a factory function for creating Option instances;
886 currently it is an alias for the Option constructor. A future version of
887 :mod:`optparse` may split Option into several classes, and :func:`make_option`
888 will pick the right class to instantiate. Do not instantiate Option directly.)
891 .. _optparse-defining-options:
896 Each Option instance represents a set of synonymous command-line option strings,
897 e.g. ``-f`` and ``--file``. You can specify any number of short or
898 long option strings, but you must specify at least one overall option string.
900 The canonical way to create an :class:`Option` instance is with the
903 .. method:: OptionParser.add_option(option)
906 To define an option with only a short option string::
908 parser.add_option("-f", attr=value, ...)
910 And to define an option with only a long option string::
912 parser.add_option("--foo", attr=value, ...)
914 The keyword arguments define attributes of the new Option object. The most
915 important option attribute is :attr:`~Option.action`, and it largely
917 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
920 An option's *action* determines what :mod:`optparse` does when it encounters
921 this option on the command-line. The standard option actions hard-coded into
925 store this option's argument (default)
928 store a constant value, pre-set via :attr:`Option.const`
937 append this option's argument to a list
940 append a constant value to a list, pre-set via :attr:`Option.const`
952 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
953 attributes; see :ref:`optparse-standard-option-actions`.)
964 :meth:`OptionParser.parse_args` (as described in :ref:`optparse-parsing-arguments`).
966 Option
968 according to the :attr:`~Option.dest` (destination) option attribute.
980 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
982 and the command-line being parsed includes any of the following::
984 -ffoo
985 -f foo
986 --file=foo
987 --file foo
989 then :mod:`optparse`, on seeing this option, will do the equivalent of ::
993 The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
994 as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
998 .. _optparse-option-attributes:
1000 Option attributes
1003 .. class:: Option
1011 The following option attributes may be passed as keyword arguments to
1012 :meth:`OptionParser.add_option`. If you pass an option attribute that is not
1013 relevant to a particular option, or fail to pass a required option attribute,
1016 .. attribute:: Option.action
1020 Determines :mod:`optparse`'s behaviour when this option is seen on the
1022 <optparse-standard-option-actions>`.
1024 .. attribute:: Option.type
1028 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1029 the available option types are documented :ref:`here
1030 <optparse-standard-option-types>`.
1032 .. attribute:: Option.dest
1034 (default: derived from option strings)
1036 If the option's action implies writing or modifying a value somewhere, this
1037 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1041 .. attribute:: Option.default
1043 The value to use for this option's destination if the option is not seen on
1046 .. attribute:: Option.nargs
1050 How many arguments of type :attr:`~Option.type` should be consumed when this
1051 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1052 :attr:`~Option.dest`.
1054 .. attribute:: Option.const
1058 .. attribute:: Option.choices
1063 .. attribute:: Option.callback
1065 For options with action ``"callback"``, the callable to call when this option
1066 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1069 .. attribute:: Option.callback_args
1070 Option.callback_kwargs
1075 .. attribute:: Option.help
1077 Help text to print for this option when listing all available options after
1078 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
1079 no help text is supplied, the option will be listed without help text. To
1080 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1082 .. attribute:: Option.metavar
1084 (default: derived from option strings)
1086 Stand-in for the option argument(s) to use when printing help text. See
1087 section :ref:`optparse-tutorial` for an example.
1090 .. _optparse-standard-option-actions:
1092 Standard option actions
1095 The various option actions all have slightly different requirements and effects.
1096 Most actions have several relevant option attributes which you may specify to
1098 must specify for any option using that action.
1100 * ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1101 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1103 The option must be followed by an argument, which is converted to a value
1104 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1105 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1106 command line; all will be converted according to :attr:`~Option.type` and
1107 stored to :attr:`~Option.dest` as a tuple. See the
1108 :ref:`optparse-standard-option-types` section.
1110 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1113 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
1115 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
1116 from the first long option string (e.g., ``--foo-bar`` implies
1117 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
1118 destination from the first short option string (e.g., ``-f`` implies ``f``).
1122 parser.add_option("-f")
1123 parser.add_option("-p", type="float", nargs=3, dest="point")
1127 -f foo.txt -p 1 -3.5 4 -fbar.txt
1132 options.point = (1.0, -3.5, 4.0)
1135 * ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1136 :attr:`~Option.dest`]
1138 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
1142 parser.add_option("-q", "--quiet",
1144 parser.add_option("-v", "--verbose",
1146 parser.add_option("--noisy",
1149 If ``--noisy`` is seen, :mod:`optparse` will set ::
1153 * ``"store_true"`` [relevant: :attr:`~Option.dest`]
1156 :attr:`~Option.dest`.
1158 * ``"store_false"`` [relevant: :attr:`~Option.dest`]
1164 parser.add_option("--clobber", action="store_true", dest="clobber")
1165 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1167 * ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1168 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1170 The option must be followed by an argument, which is appended to the list in
1171 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1173 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1174 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1175 is appended to :attr:`~Option.dest`.
1177 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1182 parser.add_option("-t", "--tracks", action="append", type="int")
1184 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
1190 If, a little later on, ``--tracks=4`` is seen, it does::
1195 option. This means that any default value specified must have an ``append``
1196 method. It also means that if the default value is non-empty, the default
1197 elements will be present in the parsed value for the option, with any values
1200 >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
1201 >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
1205 * ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1206 :attr:`~Option.dest`]
1208 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1209 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1210 ``None``, and an empty list is automatically created the first time the option
1213 * ``"count"`` [relevant: :attr:`~Option.dest`]
1215 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1216 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1221 parser.add_option("-v", action="count", dest="verbosity")
1223 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
1229 Every subsequent occurrence of ``-v`` results in ::
1233 * ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1234 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1235 :attr:`~Option.callback_kwargs`]
1237 Call the function specified by :attr:`~Option.callback`, which is called as ::
1239 func(option, opt_str, value, parser, *args, **kwargs)
1241 See section :ref:`optparse-option-callbacks` for more detail.
1245 Prints a complete help message for all the options in the current option
1247 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1248 option.
1250 If no :attr:`~Option.help` string is supplied for an option, it will still be
1251 listed in the help message. To omit an option entirely, use the special value
1254 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1261 # usually, a help option is added automatically, but that can
1265 parser.add_option("-h", "--help", action="help")
1266 parser.add_option("-v", action="store_true", dest="verbose",
1268 parser.add_option("--file", dest="filename",
1270 parser.add_option("--secret", help=SUPPRESS_HELP)
1272 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
1276 .. code-block:: text
1281 -h, --help Show this help message and exit
1282 -v Be moderately verbose
1283 --file=FILENAME Input file to read data from
1294 :attr:`~Option.help` options, you will rarely create ``version`` options,
1298 .. _optparse-standard-option-types:
1300 Standard option types
1303 :mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1305 option types, see section :ref:`optparse-extending-optparse`.
1308 the command line is stored in the destination (or passed to the callback) as-is.
1325 ``"float"`` and ``"complex"`` option arguments are converted directly with
1326 :func:`float` and :func:`complex`, with similar error-handling.
1329 :attr:`~Option.choices` option attribute (a sequence of strings) defines the
1330 set of allowed option arguments. :func:`optparse.check_choice` compares
1331 user-supplied option arguments against this master list and raises
1335 .. _optparse-parsing-arguments:
1351 an :class:`optparse.Values` object to store option arguments in (default: a
1352 new instance of :class:`Values`) -- if you give an existing object, the
1353 option defaults will not be initialized on it
1366 for every option argument stored to an option destination) and returned by
1370 OptionParser's :meth:`error` method with an appropriate end-user error message.
1372 traditional Unix exit status for command-line errors).
1375 .. _optparse-querying-manipulating-option-parser:
1377 Querying and manipulating your option parser
1380 The default behavior of the option parser can be customized slightly, and you
1381 can also poke around your option parser and see what's there. OptionParser
1386 Set parsing to stop on the first non-option. For example, if ``-a`` and
1387 ``-b`` are both simple options that take no arguments, :mod:`optparse`
1390 prog -a arg1 -b arg2
1394 prog -a -b arg1 arg2
1397 restores traditional Unix syntax, where option parsing stops with the first
1398 non-option argument.
1406 Set parsing to not stop on the first non-option, allowing interspersing
1411 Returns the Option instance with the option string *opt_str*, or ``None`` if
1412 no options have that option string.
1416 Return ``True`` if the OptionParser has an option with option string *opt_str*
1417 (e.g., ``-q`` or ``--verbose``).
1421 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1422 option is removed. If that option provided any other option strings, all of
1423 those option strings become invalid. If *opt_str* does not occur in any
1424 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
1427 .. _optparse-conflicts-between-options:
1432 If you're not careful, it's easy to define options with conflicting option
1435 parser.add_option("-n", "--dry-run", ...)
1437 parser.add_option("-n", "--noisy", ...)
1442 Every time you add an option, :mod:`optparse` checks for conflicts with existing
1443 options. If it finds any, it invokes the current conflict-handling mechanism.
1444 You can set the conflict-handling mechanism either in the constructor::
1455 assume option conflicts are a programming error and raise
1459 resolve option conflicts intelligently (see below)
1466 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1467 parser.add_option("-n", "--noisy", ..., help="be noisy")
1469 At this point, :mod:`optparse` detects that a previously added option is already
1470 using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1471 it resolves the situation by removing ``-n`` from the earlier option's list of
1472 option strings. Now ``--dry-run`` is the only way for the user to activate
1473 that option. If the user asks for help, the help message will reflect that::
1476 --dry-run do no harm
1478 -n, --noisy be noisy
1480 It's possible to whittle away the option strings for a previously added option
1481 until there are none left, and the user has no way of invoking that option from
1482 the command-line. In that case, :mod:`optparse` removes that option completely,
1486 parser.add_option("--dry-run", ..., help="new dry-run option")
1488 At this point, the original ``-n``/``--dry-run`` option is no longer
1493 -n, --noisy be noisy
1494 --dry-run new dry-run option
1497 .. _optparse-cleanup:
1506 long-running applications where large object graphs are reachable from your
1510 .. _optparse-other-methods:
1537 Set default values for several option destinations at once. Using
1543 parser.add_option("--advanced", action="store_const",
1546 parser.add_option("--novice", action="store_const",
1553 parser.add_option("--advanced", action="store_const",
1555 parser.add_option("--novice", action="store_const",
1559 .. _optparse-option-callbacks:
1561 Option Callbacks
1562 ----------------
1564 When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1565 needs, you have two choices: extend :mod:`optparse` or define a callback option.
1569 There are two steps to defining a callback option:
1571 * define the option itself using the ``"callback"`` action
1577 .. _optparse-defining-callback-option:
1579 Defining a callback option
1582 As always, the easiest way to define a callback option is by using the
1583 :meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1584 only option attribute you must specify is ``callback``, the function to call::
1586 parser.add_option("-c", action="callback", callback=my_callback)
1589 defined ``my_callback()`` when you create this callback option. In this simple
1590 case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
1591 which usually means that the option takes no arguments---the mere presence of
1592 ``-c`` on the command-line is all it needs to know. In some
1594 number of command-line arguments. This is where writing callbacks gets tricky;
1599 :attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1602 def my_callback(option, opt, value, parser):
1606 There are several other option attributes that you can supply when you define a
1607 callback option:
1609 :attr:`~Option.type`
1612 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1615 :attr:`~Option.nargs`
1617 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1618 :attr:`~Option.type`. It then passes a tuple of converted values to your
1621 :attr:`~Option.callback_args`
1624 :attr:`~Option.callback_kwargs`
1628 .. _optparse-how-callbacks-called:
1635 func(option, opt_str, value, parser, *args, **kwargs)
1639 ``option``
1640 is the Option instance that's calling the callback
1643 is the option string seen on the command-line that's triggering the callback.
1644 (If an abbreviated long option was used, ``opt_str`` will be the full,
1645 canonical option string---e.g. if the user puts ``--foo`` on the
1646 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
1647 ``"--foobar"``.)
1650 is the argument to this option seen on the command-line. :mod:`optparse` will
1651 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1652 the type implied by the option's type. If :attr:`~Option.type` for this option is
1653 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
1662 consumed but are neither options nor option arguments. Feel free to modify
1673 the object where option values are by default stored (an instance of
1675 rest of :mod:`optparse` for storing option values; you don't need to mess
1677 value(s) of any options already encountered on the command-line.
1681 :attr:`~Option.callback_args` option attribute.
1685 :attr:`~Option.callback_kwargs`.
1688 .. _optparse-raising-errors-in-callback:
1694 problems with the option or its argument(s). :mod:`optparse` catches this and
1696 message should be clear, concise, accurate, and mention the option at fault.
1700 .. _optparse-callback-example-1:
1705 Here's an example of a callback option that takes no arguments, and simply
1706 records that the option was seen::
1708 def record_foo_seen(option, opt_str, value, parser):
1711 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1716 .. _optparse-callback-example-2:
1718 Callback example 2: check option order
1721 Here's a slightly more interesting example: record the fact that ``-a`` is
1722 seen, but blow up if it comes after ``-b`` in the command-line. ::
1724 def check_order(option, opt_str, value, parser):
1726 raise OptionValueError("can't use -a after -b")
1729 parser.add_option("-a", action="callback", callback=check_order)
1730 parser.add_option("-b", action="store_true", dest="b")
1733 .. _optparse-callback-example-3:
1735 Callback example 3: check option order (generalized)
1738 If you want to re-use this callback for several similar options (set a flag, but
1739 blow up if ``-b`` has already been seen), it needs a bit of work: the error
1742 def check_order(option, opt_str, value, parser):
1744 raise OptionValueError("can't use %s after -b" % opt_str)
1745 setattr(parser.values, option.dest, 1)
1747 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1748 parser.add_option("-b", action="store_true", dest="b")
1749 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1752 .. _optparse-callback-example-4:
1757 Of course, you could put any condition in there---you're not limited to checking
1758 the values of already-defined options. For example, if you have options that
1761 def check_moon(option, opt_str, value, parser):
1763 raise OptionValueError("%s option invalid when moon is full"
1765 setattr(parser.values, option.dest, 1)
1767 parser.add_option("--foo",
1773 .. _optparse-callback-example-5:
1779 a fixed number of arguments. Specifying that a callback option takes arguments
1780 is similar to defining a ``"store"`` or ``"append"`` option: if you define
1781 :attr:`~Option.type`, then the option takes one argument that must be
1782 convertible to that type; if you further define :attr:`~Option.nargs`, then the
1783 option takes :attr:`~Option.nargs` arguments.
1787 def store_value(option, opt_str, value, parser):
1788 setattr(parser.values, option.dest, value)
1790 parser.add_option("--foo",
1799 .. _optparse-callback-example-6:
1804 Things get hairy when you want an option to take a variable number of arguments.
1806 built-in capabilities for it. And you have to deal with certain intricacies of
1807 conventional Unix command-line parsing that :mod:`optparse` normally handles for
1809 ``--`` and ``-`` arguments:
1811 * either ``--`` or ``-`` can be option arguments
1813 * bare ``--`` (if not the argument to some option): halt command-line
1814 processing and discard the ``--``
1816 * bare ``-`` (if not the argument to some option): halt command-line
1817 processing but keep the ``-`` (append it to ``parser.largs``)
1819 If you want an option that takes a variable number of arguments, there are
1821 choose will be based on which trade-offs you're willing to make for your
1825 Nevertheless, here's a stab at a callback for an option with variable
1828 def vararg_callback(option, opt_str, value, parser):
1840 # stop on --foo like options
1841 if arg[:2] == "--" and len(arg) > 2:
1843 # stop on -a, but not on -3 or -3.0
1844 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1849 setattr(parser.values, option.dest, value)
1852 parser.add_option("-c", "--callback", dest="vararg_attr",
1856 .. _optparse-extending-optparse:
1859 -------------------------
1862 command-line options are the action and type of each option, the most likely
1866 .. _optparse-adding-new-types:
1872 :class:`Option` class. This class has a couple of attributes that define
1873 :mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
1875 .. attribute:: Option.TYPES
1880 .. attribute:: Option.TYPE_CHECKER
1882 A dictionary mapping type names to type-checking functions. A type-checking
1885 def check_mytype(option, opt, value)
1887 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1888 (e.g., ``-f``), and ``value`` is the string from the command line that must
1891 a type-checking function will wind up in the OptionValues instance returned
1895 Your type-checking function should raise :exc:`OptionValueError` if it
1897 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1901 Here's a silly example that demonstrates adding a ``"complex"`` option type to
1902 parse Python-style complex numbers on the command line. (This is even sillier
1903 than it used to be, because :mod:`optparse` 1.3 added built-in support for
1909 from optparse import Option, OptionValueError
1911 You need to define your type-checker first, since it's referred to later (in the
1912 :attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
1914 def check_complex(option, opt, value):
1919 "option %s: invalid complex value: %r" % (opt, value))
1921 Finally, the Option subclass::
1923 class MyOption (Option):
1924 TYPES = Option.TYPES + ("complex",)
1925 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1928 (If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1929 up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1930 Option class. This being Python, nothing stops you from doing that except good
1933 That's it! Now you can write a script that uses the new option type just like
1934 any other :mod:`optparse`\ -based script, except you have to instruct your
1935 OptionParser to use MyOption instead of Option::
1938 parser.add_option("-c", type="complex")
1940 Alternately, you can build your own option list and pass it to OptionParser; if
1942 OptionParser which option class to use::
1944 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1948 .. _optparse-adding-new-actions:
1958 current OptionValues instance; these options require a :attr:`~Option.dest`
1959 attribute to be supplied to the Option constructor.
1964 These options require a :attr:`~Option.type` attribute to the Option
1972 of the following class attributes of Option (all are lists of strings):
1974 .. attribute:: Option.ACTIONS
1978 .. attribute:: Option.STORE_ACTIONS
1982 .. attribute:: Option.TYPED_ACTIONS
1986 .. attribute:: Option.ALWAYS_TYPED_ACTIONS
1993 In order to actually implement your new action, you must override Option's
1997 ``"append"`` action, but instead of taking a single value from the command-line
1999 a single comma-delimited string, and extend an existing list with them. That
2000 is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
2003 --names=foo,bar --names blah --names ding,dong
2009 Again we define a subclass of Option::
2011 class MyOption(Option):
2013 ACTIONS = Option.ACTIONS + ("extend",)
2014 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
2015 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
2016 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
2023 Option.take_action(
2028 * ``"extend"`` both expects a value on the command-line and stores that value
2029 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
2030 :attr:`~Option.TYPED_ACTIONS`.
2034 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
2037 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
2052 about setting a default value for the option destinations in question; they
2057 ----------
2061 Raised if an :class:`Option` instance is created with invalid or
2070 Raised if an invalid option value is encountered on the command line.
2074 Raised if an invalid option is passed on the command line.
2078 Raised if an ambiguous option is passed on the command line.