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 VMS, MS-DOS, and/or Windows.
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:
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
532 * options that take a value indicate this fact in their automatically-generated
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)
937 append this option's argument to a list
952 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
953 attributes; see :ref:`optparse-standard-option-actions`.)
957 ``options`` (it happens to be an instance of :class:`optparse.Values`). Option
959 according to the :attr:`~Option.dest` (destination) option attribute.
971 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
973 and the command-line being parsed includes any of the following::
975 -ffoo
976 -f foo
977 --file=foo
978 --file foo
980 then :mod:`optparse`, on seeing this option, will do the equivalent of ::
984 The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
985 as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
989 .. _optparse-option-attributes:
991 Option attributes
994 The following option attributes may be passed as keyword arguments to
995 :meth:`OptionParser.add_option`. If you pass an option attribute that is not
996 relevant to a particular option, or fail to pass a required option attribute,
999 .. attribute:: Option.action
1003 Determines :mod:`optparse`'s behaviour when this option is seen on the
1005 <optparse-standard-option-actions>`.
1007 .. attribute:: Option.type
1011 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1012 the available option types are documented :ref:`here
1013 <optparse-standard-option-types>`.
1015 .. attribute:: Option.dest
1017 (default: derived from option strings)
1019 If the option's action implies writing or modifying a value somewhere, this
1020 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1024 .. attribute:: Option.default
1026 The value to use for this option's destination if the option is not seen on
1029 .. attribute:: Option.nargs
1033 How many arguments of type :attr:`~Option.type` should be consumed when this
1034 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1035 :attr:`~Option.dest`.
1037 .. attribute:: Option.const
1041 .. attribute:: Option.choices
1046 .. attribute:: Option.callback
1048 For options with action ``"callback"``, the callable to call when this option
1049 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1052 .. attribute:: Option.callback_args
1053 Option.callback_kwargs
1058 .. attribute:: Option.help
1060 Help text to print for this option when listing all available options after
1061 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
1062 no help text is supplied, the option will be listed without help text. To
1063 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1065 .. attribute:: Option.metavar
1067 (default: derived from option strings)
1069 Stand-in for the option argument(s) to use when printing help text. See
1070 section :ref:`optparse-tutorial` for an example.
1073 .. _optparse-standard-option-actions:
1075 Standard option actions
1078 The various option actions all have slightly different requirements and effects.
1079 Most actions have several relevant option attributes which you may specify to
1081 must specify for any option using that action.
1083 * ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1084 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1086 The option must be followed by an argument, which is converted to a value
1087 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1088 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1089 command line; all will be converted according to :attr:`~Option.type` and
1090 stored to :attr:`~Option.dest` as a tuple. See the
1091 :ref:`optparse-standard-option-types` section.
1093 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1096 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
1098 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
1099 from the first long option string (e.g., ``--foo-bar`` implies
1100 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
1101 destination from the first short option string (e.g., ``-f`` implies ``f``).
1105 parser.add_option("-f")
1106 parser.add_option("-p", type="float", nargs=3, dest="point")
1110 -f foo.txt -p 1 -3.5 4 -fbar.txt
1115 options.point = (1.0, -3.5, 4.0)
1118 * ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1119 :attr:`~Option.dest`]
1121 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
1125 parser.add_option("-q", "--quiet",
1127 parser.add_option("-v", "--verbose",
1129 parser.add_option("--noisy",
1132 If ``--noisy`` is seen, :mod:`optparse` will set ::
1136 * ``"store_true"`` [relevant: :attr:`~Option.dest`]
1139 :attr:`~Option.dest`.
1141 * ``"store_false"`` [relevant: :attr:`~Option.dest`]
1147 parser.add_option("--clobber", action="store_true", dest="clobber")
1148 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1150 * ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1151 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1153 The option must be followed by an argument, which is appended to the list in
1154 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1156 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1157 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1158 is appended to :attr:`~Option.dest`.
1160 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1165 parser.add_option("-t", "--tracks", action="append", type="int")
1167 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
1173 If, a little later on, ``--tracks=4`` is seen, it does::
1178 option. This means that any default value specified must have an ``append``
1179 method. It also means that if the default value is non-empty, the default
1180 elements will be present in the parsed value for the option, with any values
1183 >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
1184 >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
1188 * ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1189 :attr:`~Option.dest`]
1191 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1192 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1193 ``None``, and an empty list is automatically created the first time the option
1196 * ``"count"`` [relevant: :attr:`~Option.dest`]
1198 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1199 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1204 parser.add_option("-v", action="count", dest="verbosity")
1206 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
1212 Every subsequent occurrence of ``-v`` results in ::
1216 * ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1217 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1218 :attr:`~Option.callback_kwargs`]
1220 Call the function specified by :attr:`~Option.callback`, which is called as ::
1222 func(option, opt_str, value, parser, *args, **kwargs)
1224 See section :ref:`optparse-option-callbacks` for more detail.
1228 Prints a complete help message for all the options in the current option
1230 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1231 option.
1233 If no :attr:`~Option.help` string is supplied for an option, it will still be
1234 listed in the help message. To omit an option entirely, use the special value
1237 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1244 # usually, a help option is added automatically, but that can
1248 parser.add_option("-h", "--help", action="help")
1249 parser.add_option("-v", action="store_true", dest="verbose",
1251 parser.add_option("--file", dest="filename",
1253 parser.add_option("--secret", help=SUPPRESS_HELP)
1255 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
1259 .. code-block:: text
1264 -h, --help Show this help message and exit
1265 -v Be moderately verbose
1266 --file=FILENAME Input file to read data from
1277 :attr:`~Option.help` options, you will rarely create ``version`` options,
1281 .. _optparse-standard-option-types:
1283 Standard option types
1286 :mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1288 option types, see section :ref:`optparse-extending-optparse`.
1291 the command line is stored in the destination (or passed to the callback) as-is.
1308 ``"float"`` and ``"complex"`` option arguments are converted directly with
1309 :func:`float` and :func:`complex`, with similar error-handling.
1312 :attr:`~Option.choices` option attribute (a sequence of strings) defines the
1313 set of allowed option arguments. :func:`optparse.check_choice` compares
1314 user-supplied option arguments against this master list and raises
1318 .. _optparse-parsing-arguments:
1334 an :class:`optparse.Values` object to store option arguments in (default: a
1335 new instance of :class:`Values`) -- if you give an existing object, the
1336 option defaults will not be initialized on it
1349 for every option argument stored to an option destination) and returned by
1353 OptionParser's :meth:`error` method with an appropriate end-user error message.
1355 traditional Unix exit status for command-line errors).
1358 .. _optparse-querying-manipulating-option-parser:
1360 Querying and manipulating your option parser
1363 The default behavior of the option parser can be customized slightly, and you
1364 can also poke around your option parser and see what's there. OptionParser
1369 Set parsing to stop on the first non-option. For example, if ``-a`` and
1370 ``-b`` are both simple options that take no arguments, :mod:`optparse`
1373 prog -a arg1 -b arg2
1377 prog -a -b arg1 arg2
1380 restores traditional Unix syntax, where option parsing stops with the first
1381 non-option argument.
1389 Set parsing to not stop on the first non-option, allowing interspersing
1394 Returns the Option instance with the option string *opt_str*, or ``None`` if
1395 no options have that option string.
1399 Return ``True`` if the OptionParser has an option with option string *opt_str*
1400 (e.g., ``-q`` or ``--verbose``).
1404 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1405 option is removed. If that option provided any other option strings, all of
1406 those option strings become invalid. If *opt_str* does not occur in any
1407 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
1410 .. _optparse-conflicts-between-options:
1415 If you're not careful, it's easy to define options with conflicting option
1418 parser.add_option("-n", "--dry-run", ...)
1420 parser.add_option("-n", "--noisy", ...)
1425 Every time you add an option, :mod:`optparse` checks for conflicts with existing
1426 options. If it finds any, it invokes the current conflict-handling mechanism.
1427 You can set the conflict-handling mechanism either in the constructor::
1438 assume option conflicts are a programming error and raise
1442 resolve option conflicts intelligently (see below)
1449 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1450 parser.add_option("-n", "--noisy", ..., help="be noisy")
1452 At this point, :mod:`optparse` detects that a previously-added option is already
1453 using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1454 it resolves the situation by removing ``-n`` from the earlier option's list of
1455 option strings. Now ``--dry-run`` is the only way for the user to activate
1456 that option. If the user asks for help, the help message will reflect that::
1459 --dry-run do no harm
1461 -n, --noisy be noisy
1463 It's possible to whittle away the option strings for a previously-added option
1464 until there are none left, and the user has no way of invoking that option from
1465 the command-line. In that case, :mod:`optparse` removes that option completely,
1469 parser.add_option("--dry-run", ..., help="new dry-run option")
1471 At this point, the original ``-n``/``--dry-run`` option is no longer
1476 -n, --noisy be noisy
1477 --dry-run new dry-run option
1480 .. _optparse-cleanup:
1489 long-running applications where large object graphs are reachable from your
1493 .. _optparse-other-methods:
1520 Set default values for several option destinations at once. Using
1526 parser.add_option("--advanced", action="store_const",
1529 parser.add_option("--novice", action="store_const",
1536 parser.add_option("--advanced", action="store_const",
1538 parser.add_option("--novice", action="store_const",
1542 .. _optparse-option-callbacks:
1544 Option Callbacks
1545 ----------------
1547 When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1548 needs, you have two choices: extend :mod:`optparse` or define a callback option.
1552 There are two steps to defining a callback option:
1554 * define the option itself using the ``"callback"`` action
1560 .. _optparse-defining-callback-option:
1562 Defining a callback option
1565 As always, the easiest way to define a callback option is by using the
1566 :meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1567 only option attribute you must specify is ``callback``, the function to call::
1569 parser.add_option("-c", action="callback", callback=my_callback)
1572 defined ``my_callback()`` when you create this callback option. In this simple
1573 case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
1574 which usually means that the option takes no arguments---the mere presence of
1575 ``-c`` on the command-line is all it needs to know. In some
1577 number of command-line arguments. This is where writing callbacks gets tricky;
1582 :attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1585 def my_callback(option, opt, value, parser):
1589 There are several other option attributes that you can supply when you define a
1590 callback option:
1592 :attr:`~Option.type`
1595 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1598 :attr:`~Option.nargs`
1600 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1601 :attr:`~Option.type`. It then passes a tuple of converted values to your
1604 :attr:`~Option.callback_args`
1607 :attr:`~Option.callback_kwargs`
1611 .. _optparse-how-callbacks-called:
1618 func(option, opt_str, value, parser, *args, **kwargs)
1622 ``option``
1623 is the Option instance that's calling the callback
1626 is the option string seen on the command-line that's triggering the callback.
1627 (If an abbreviated long option was used, ``opt_str`` will be the full,
1628 canonical option string---e.g. if the user puts ``--foo`` on the
1629 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
1630 ``"--foobar"``.)
1633 is the argument to this option seen on the command-line. :mod:`optparse` will
1634 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1635 the type implied by the option's type. If :attr:`~Option.type` for this option is
1636 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
1645 consumed but are neither options nor option arguments. Feel free to modify
1656 the object where option values are by default stored (an instance of
1658 rest of :mod:`optparse` for storing option values; you don't need to mess
1660 value(s) of any options already encountered on the command-line.
1664 :attr:`~Option.callback_args` option attribute.
1668 :attr:`~Option.callback_kwargs`.
1671 .. _optparse-raising-errors-in-callback:
1677 problems with the option or its argument(s). :mod:`optparse` catches this and
1679 message should be clear, concise, accurate, and mention the option at fault.
1683 .. _optparse-callback-example-1:
1688 Here's an example of a callback option that takes no arguments, and simply
1689 records that the option was seen::
1691 def record_foo_seen(option, opt_str, value, parser):
1694 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1699 .. _optparse-callback-example-2:
1701 Callback example 2: check option order
1704 Here's a slightly more interesting example: record the fact that ``-a`` is
1705 seen, but blow up if it comes after ``-b`` in the command-line. ::
1707 def check_order(option, opt_str, value, parser):
1709 raise OptionValueError("can't use -a after -b")
1712 parser.add_option("-a", action="callback", callback=check_order)
1713 parser.add_option("-b", action="store_true", dest="b")
1716 .. _optparse-callback-example-3:
1718 Callback example 3: check option order (generalized)
1721 If you want to re-use this callback for several similar options (set a flag, but
1722 blow up if ``-b`` has already been seen), it needs a bit of work: the error
1725 def check_order(option, opt_str, value, parser):
1727 raise OptionValueError("can't use %s after -b" % opt_str)
1728 setattr(parser.values, option.dest, 1)
1730 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1731 parser.add_option("-b", action="store_true", dest="b")
1732 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1735 .. _optparse-callback-example-4:
1740 Of course, you could put any condition in there---you're not limited to checking
1741 the values of already-defined options. For example, if you have options that
1744 def check_moon(option, opt_str, value, parser):
1746 raise OptionValueError("%s option invalid when moon is full"
1748 setattr(parser.values, option.dest, 1)
1750 parser.add_option("--foo",
1756 .. _optparse-callback-example-5:
1762 a fixed number of arguments. Specifying that a callback option takes arguments
1763 is similar to defining a ``"store"`` or ``"append"`` option: if you define
1764 :attr:`~Option.type`, then the option takes one argument that must be
1765 convertible to that type; if you further define :attr:`~Option.nargs`, then the
1766 option takes :attr:`~Option.nargs` arguments.
1770 def store_value(option, opt_str, value, parser):
1771 setattr(parser.values, option.dest, value)
1773 parser.add_option("--foo",
1782 .. _optparse-callback-example-6:
1787 Things get hairy when you want an option to take a variable number of arguments.
1789 built-in capabilities for it. And you have to deal with certain intricacies of
1790 conventional Unix command-line parsing that :mod:`optparse` normally handles for
1792 ``--`` and ``-`` arguments:
1794 * either ``--`` or ``-`` can be option arguments
1796 * bare ``--`` (if not the argument to some option): halt command-line
1797 processing and discard the ``--``
1799 * bare ``-`` (if not the argument to some option): halt command-line
1800 processing but keep the ``-`` (append it to ``parser.largs``)
1802 If you want an option that takes a variable number of arguments, there are
1804 choose will be based on which trade-offs you're willing to make for your
1808 Nevertheless, here's a stab at a callback for an option with variable
1811 def vararg_callback(option, opt_str, value, parser):
1823 # stop on --foo like options
1824 if arg[:2] == "--" and len(arg) > 2:
1826 # stop on -a, but not on -3 or -3.0
1827 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1832 setattr(parser.values, option.dest, value)
1835 parser.add_option("-c", "--callback", dest="vararg_attr",
1839 .. _optparse-extending-optparse:
1842 -------------------------
1845 command-line options are the action and type of each option, the most likely
1849 .. _optparse-adding-new-types:
1855 :class:`Option` class. This class has a couple of attributes that define
1856 :mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
1858 .. attribute:: Option.TYPES
1863 .. attribute:: Option.TYPE_CHECKER
1865 A dictionary mapping type names to type-checking functions. A type-checking
1868 def check_mytype(option, opt, value)
1870 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1871 (e.g., ``-f``), and ``value`` is the string from the command line that must
1874 a type-checking function will wind up in the OptionValues instance returned
1878 Your type-checking function should raise :exc:`OptionValueError` if it
1880 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1884 Here's a silly example that demonstrates adding a ``"complex"`` option type to
1885 parse Python-style complex numbers on the command line. (This is even sillier
1886 than it used to be, because :mod:`optparse` 1.3 added built-in support for
1892 from optparse import Option, OptionValueError
1894 You need to define your type-checker first, since it's referred to later (in the
1895 :attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
1897 def check_complex(option, opt, value):
1902 "option %s: invalid complex value: %r" % (opt, value))
1904 Finally, the Option subclass::
1906 class MyOption (Option):
1907 TYPES = Option.TYPES + ("complex",)
1908 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1911 (If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1912 up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1913 Option class. This being Python, nothing stops you from doing that except good
1916 That's it! Now you can write a script that uses the new option type just like
1917 any other :mod:`optparse`\ -based script, except you have to instruct your
1918 OptionParser to use MyOption instead of Option::
1921 parser.add_option("-c", type="complex")
1923 Alternately, you can build your own option list and pass it to OptionParser; if
1925 OptionParser which option class to use::
1927 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1931 .. _optparse-adding-new-actions:
1941 current OptionValues instance; these options require a :attr:`~Option.dest`
1942 attribute to be supplied to the Option constructor.
1947 These options require a :attr:`~Option.type` attribute to the Option
1955 of the following class attributes of Option (all are lists of strings):
1957 .. attribute:: Option.ACTIONS
1961 .. attribute:: Option.STORE_ACTIONS
1965 .. attribute:: Option.TYPED_ACTIONS
1969 .. attribute:: Option.ALWAYS_TYPED_ACTIONS
1976 In order to actually implement your new action, you must override Option's
1980 ``"append"`` action, but instead of taking a single value from the command-line
1982 a single comma-delimited string, and extend an existing list with them. That
1983 is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
1986 --names=foo,bar --names blah --names ding,dong
1992 Again we define a subclass of Option::
1994 class MyOption(Option):
1996 ACTIONS = Option.ACTIONS + ("extend",)
1997 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1998 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1999 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
2006 Option.take_action(
2011 * ``"extend"`` both expects a value on the command-line and stores that value
2012 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
2013 :attr:`~Option.TYPED_ACTIONS`.
2017 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
2020 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
2035 about setting a default value for the option destinations in question; they