Lines Matching full:option
5 :synopsis: Command-line option parsing library.
107 option
115 only two option syntaxes provided by :mod:`optparse`.
117 Some other option syntaxes that the world has seen include:
132 These option syntaxes are not supported by :mod:`optparse`, and they never
137 option argument
138 an argument that follows an option, is closely associated with that option,
139 and is consumed from the argument list when that option is. With
140 :mod:`optparse`, option arguments may either be in a separate argument from
141 their option:
155 Typically, a given option either takes an argument or it doesn't. Lots of
156 people want an "optional option arguments" feature, meaning that some options
159 an optional argument and ``-b`` is another option entirely, how do we
168 required option
169 an option that must be supplied on the command-line; note that the phrase
170 "required option" is self-contradictory in English. :mod:`optparse` doesn't
179 takes one argument, ``report.txt`` is an option argument. ``foo`` and
265 Each option has one or more option strings, such as ``-f`` or ``--file``,
266 and several option attributes that tell :mod:`optparse` what to expect and what
267 to do when it encounters that option on the command line.
269 Typically, each option will have one short option string and one long option
274 You're free to define as many short option strings and as many long option
275 strings as you like (including zero), as long as there is at least one option
278 The option strings passed to :meth:`OptionParser.add_option` are effectively
280 option defined by that call. For brevity, we will frequently refer to
281 *encountering an option* on the command line; in reality, :mod:`optparse`
282 encounters *option strings* and looks up options from them.
297 option
301 This tutorial section only covers the four most important option attributes:
302 :attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
303 (destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
307 .. _optparse-understanding-option-actions:
309 Understanding option actions
312 Actions tell :mod:`optparse` what to do when it encounters an option on the
319 If you don't specify an option action, :mod:`optparse` defaults to ``store``.
327 The most common option action is ``store``, which tells :mod:`optparse` to take
341 When :mod:`optparse` sees the option string ``-f``, it consumes the next
345 Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
346 Here's an option that expects an integer argument::
350 Note that this option has no long option string, which is perfectly acceptable.
353 Let's parse another fake command-line. This time, we'll jam the option argument
354 right up against the option: since ``-n42`` (one argument) is equivalent to
369 default from the option strings: if the first long option string is
371 long option strings, :mod:`optparse` looks at the first short option string: the
383 Flag options---set a variable to true or false when a particular option is
408 store a constant value, pre-set via :attr:`Option.const`
411 append this option's argument to a list
420 and section :ref:`optparse-option-callbacks`.
442 option, and these two options happen to have the same destination, this is
464 As before, the last value specified for a given option destination is the one
476 is supply a :attr:`~Option.help` value for each option, and optionally a short
512 (If the help output is triggered by a help option, :mod:`optparse` exits after
524 is then printed before the detailed option help.
530 * every option defines a help string, and doesn't worry about
535 help message, e.g. for the "mode" option::
543 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
544 resulting in this automatically generated option description::
555 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
556 default value. If an option has no default value (or the default value is
563 better help output. An :class:`OptionParser` can contain several option groups,
566 An option group is obtained using the class :class:`OptionGroup`:
579 an option to the group.
590 group.add_option("-g", action="store_true", help="Group option.")
612 -g Group option.
620 group.add_option("-g", action="store_true", help="Group option.")
650 -g Group option.
658 option groups is:
662 Return the :class:`OptionGroup` to which the short or long option
663 string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
679 automatically adds a ``--version`` option to your parser. If it encounters
680 this option on the command line, it expands your ``version`` string (by
712 calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
713 option attributes, missing option attributes, etc. These are dealt with in the
719 some user errors, such as bad option arguments (passing ``-n 4x`` where
734 Consider the first example above, where the user passes ``4x`` to an option
742 foo: error: option -n: invalid integer value: '4x'
751 foo: error: -n option requires an argument
754 option involved in the error; be sure to do the same when calling
813 help option. When :mod:`optparse` prints the usage string, it expands
819 A list of Option objects to populate the parser with. The options in
825 ``option_class`` (default: optparse.Option)
829 A version string to print when the user supplies a version option. If you
831 version option with the single option string ``--version``. The
835 Specifies what to do when options with conflicting option strings are
851 If true, :mod:`optparse` will add a help option (with option strings ``-h``
859 A paragraph of help text to print after the option help.
870 * pass it an Option instance (as returned by :func:`make_option`)
873 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
874 will create the Option instance for you
876 The other alternative is to pass a list of pre-constructed Option instances to
887 (:func:`make_option` is a factory function for creating Option instances;
888 currently it is an alias for the Option constructor. A future version of
889 :mod:`optparse` may split Option into several classes, and :func:`make_option`
890 will pick the right class to instantiate. Do not instantiate Option directly.)
898 Each Option instance represents a set of synonymous command-line option strings,
900 long option strings, but you must specify at least one overall option string.
902 The canonical way to create an :class:`Option` instance is with the
905 .. method:: OptionParser.add_option(option)
908 To define an option with only a short option string::
912 And to define an option with only a long option string::
916 The keyword arguments define attributes of the new Option object. The most
917 important option attribute is :attr:`~Option.action`, and it largely
919 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
922 An option's *action* determines what :mod:`optparse` does when it encounters
923 this option on the command-line. The standard option actions hard-coded into
927 store this option's argument (default)
930 store a constant value, pre-set via :attr:`Option.const`
939 append this option's argument to a list
942 append a constant value to a list, pre-set via :attr:`Option.const`
954 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
955 attributes; see :ref:`optparse-standard-option-actions`.)
968 Option
970 according to the :attr:`~Option.dest` (destination) option attribute.
991 then :mod:`optparse`, on seeing this option, will do the equivalent of ::
995 The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
996 as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
1000 .. _optparse-option-attributes:
1002 Option attributes
1005 .. class:: Option
1013 The following option attributes may be passed as keyword arguments to
1014 :meth:`OptionParser.add_option`. If you pass an option attribute that is not
1015 relevant to a particular option, or fail to pass a required option attribute,
1018 .. attribute:: Option.action
1022 Determines :mod:`optparse`'s behaviour when this option is seen on the
1024 <optparse-standard-option-actions>`.
1026 .. attribute:: Option.type
1030 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1031 the available option types are documented :ref:`here
1032 <optparse-standard-option-types>`.
1034 .. attribute:: Option.dest
1036 (default: derived from option strings)
1038 If the option's action implies writing or modifying a value somewhere, this
1039 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1043 .. attribute:: Option.default
1045 The value to use for this option's destination if the option is not seen on
1048 .. attribute:: Option.nargs
1052 How many arguments of type :attr:`~Option.type` should be consumed when this
1053 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1054 :attr:`~Option.dest`.
1056 .. attribute:: Option.const
1060 .. attribute:: Option.choices
1065 .. attribute:: Option.callback
1067 For options with action ``"callback"``, the callable to call when this option
1068 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1071 .. attribute:: Option.callback_args
1072 Option.callback_kwargs
1077 .. attribute:: Option.help
1079 Help text to print for this option when listing all available options after
1080 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
1081 no help text is supplied, the option will be listed without help text. To
1082 hide this option, use the special value :const:`optparse.SUPPRESS_HELP`.
1084 .. attribute:: Option.metavar
1086 (default: derived from option strings)
1088 Stand-in for the option argument(s) to use when printing help text. See
1092 .. _optparse-standard-option-actions:
1094 Standard option actions
1097 The various option actions all have slightly different requirements and effects.
1098 Most actions have several relevant option attributes which you may specify to
1100 must specify for any option using that action.
1102 * ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1103 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1105 The option must be followed by an argument, which is converted to a value
1106 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1107 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1108 command line; all will be converted according to :attr:`~Option.type` and
1109 stored to :attr:`~Option.dest` as a tuple. See the
1110 :ref:`optparse-standard-option-types` section.
1112 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1115 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
1117 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
1118 from the first long option string (e.g., ``--foo-bar`` implies
1119 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
1120 destination from the first short option string (e.g., ``-f`` implies ``f``).
1137 * ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1138 :attr:`~Option.dest`]
1140 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
1155 * ``"store_true"`` [relevant: :attr:`~Option.dest`]
1158 :attr:`~Option.dest`.
1160 * ``"store_false"`` [relevant: :attr:`~Option.dest`]
1169 * ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1170 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1172 The option must be followed by an argument, which is appended to the list in
1173 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1175 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1176 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1177 is appended to :attr:`~Option.dest`.
1179 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1197 option. This means that any default value specified must have an ``append``
1199 elements will be present in the parsed value for the option, with any values
1207 * ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1208 :attr:`~Option.dest`]
1210 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1211 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1212 ``None``, and an empty list is automatically created the first time the option
1215 * ``"count"`` [relevant: :attr:`~Option.dest`]
1217 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1218 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1235 * ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1236 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1237 :attr:`~Option.callback_kwargs`]
1239 Call the function specified by :attr:`~Option.callback`, which is called as ::
1241 func(option, opt_str, value, parser, *args, **kwargs)
1243 See section :ref:`optparse-option-callbacks` for more detail.
1247 Prints a complete help message for all the options in the current option
1249 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1250 option.
1252 If no :attr:`~Option.help` string is supplied for an option, it will still be
1253 listed in the help message. To omit an option entirely, use the special value
1256 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1263 # usually, a help option is added automatically, but that can
1296 :attr:`~Option.help` options, you will rarely create ``version`` options,
1300 .. _optparse-standard-option-types:
1302 Standard option types
1305 :mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1307 option types, see section :ref:`optparse-extending-optparse`.
1327 ``"float"`` and ``"complex"`` option arguments are converted directly with
1331 :attr:`~Option.choices` option attribute (a sequence of strings) defines the
1332 set of allowed option arguments. :func:`optparse.check_choice` compares
1333 user-supplied option arguments against this master list and raises
1355 a :class:`Values` object to store option arguments in (default: a
1357 option defaults will not be initialized on it
1370 for every option argument stored to an option destination) and returned by
1379 .. _optparse-querying-manipulating-option-parser:
1381 Querying and manipulating your option parser
1384 The default behavior of the option parser can be customized slightly, and you
1385 can also poke around your option parser and see what's there. OptionParser
1390 Set parsing to stop on the first non-option. For example, if ``-a`` and
1401 restores traditional Unix syntax, where option parsing stops with the first
1402 non-option argument.
1410 Set parsing to not stop on the first non-option, allowing interspersing
1415 Returns the Option instance with the option string *opt_str*, or ``None`` if
1416 no options have that option string.
1420 Return ``True`` if the OptionParser has an option with option string *opt_str*
1425 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1426 option is removed. If that option provided any other option strings, all of
1427 those option strings become invalid. If *opt_str* does not occur in any
1428 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
1436 If you're not careful, it's easy to define options with conflicting option
1446 Every time you add an option, :mod:`optparse` checks for conflicts with existing
1459 assume option conflicts are a programming error and raise
1463 resolve option conflicts intelligently (see below)
1473 At this point, :mod:`optparse` detects that a previously added option is already
1474 using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1475 it resolves the situation by removing ``-n`` from the earlier option's list of
1476 option strings. Now ``--dry-run`` is the only way for the user to activate
1477 that option. If the user asks for help, the help message will reflect that::
1484 It's possible to whittle away the option strings for a previously added option
1485 until there are none left, and the user has no way of invoking that option from
1486 the command-line. In that case, :mod:`optparse` removes that option completely,
1490 parser.add_option("--dry-run", ..., help="new dry-run option")
1492 At this point, the original ``-n``/``--dry-run`` option is no longer
1498 --dry-run new dry-run option
1541 Set default values for several option destinations at once. Using
1563 .. _optparse-option-callbacks:
1565 Option Callbacks
1569 needs, you have two choices: extend :mod:`optparse` or define a callback option.
1573 There are two steps to defining a callback option:
1575 * define the option itself using the ``"callback"`` action
1581 .. _optparse-defining-callback-option:
1583 Defining a callback option
1586 As always, the easiest way to define a callback option is by using the
1587 :meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1588 only option attribute you must specify is ``callback``, the function to call::
1593 defined ``my_callback()`` when you create this callback option. In this simple
1595 which usually means that the option takes no arguments---the mere presence of
1603 :attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1606 def my_callback(option, opt, value, parser):
1610 There are several other option attributes that you can supply when you define a
1611 callback option:
1613 :attr:`~Option.type`
1616 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1619 :attr:`~Option.nargs`
1621 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1622 :attr:`~Option.type`. It then passes a tuple of converted values to your
1625 :attr:`~Option.callback_args`
1628 :attr:`~Option.callback_kwargs`
1639 func(option, opt_str, value, parser, *args, **kwargs)
1643 ``option``
1644 is the Option instance that's calling the callback
1647 is the option string seen on the command-line that's triggering the callback.
1648 (If an abbreviated long option was used, ``opt_str`` will be the full,
1649 canonical option string---e.g. if the user puts ``--foo`` on the
1654 is the argument to this option seen on the command-line. :mod:`optparse` will
1655 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1656 the type implied by the option's type. If :attr:`~Option.type` for this option is
1657 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
1666 consumed but are neither options nor option arguments. Feel free to modify
1677 the object where option values are by default stored (an instance of
1679 rest of :mod:`optparse` for storing option values; you don't need to mess
1685 :attr:`~Option.callback_args` option attribute.
1689 :attr:`~Option.callback_kwargs`.
1698 problems with the option or its argument(s). :mod:`optparse` catches this and
1700 message should be clear, concise, accurate, and mention the option at fault.
1709 Here's an example of a callback option that takes no arguments, and simply
1710 records that the option was seen::
1712 def record_foo_seen(option, opt_str, value, parser):
1722 Callback example 2: check option order
1728 def check_order(option, opt_str, value, parser):
1739 Callback example 3: check option order (generalized)
1746 def check_order(option, opt_str, value, parser):
1749 setattr(parser.values, option.dest, 1)
1765 def check_moon(option, opt_str, value, parser):
1767 raise OptionValueError("%s option invalid when moon is full"
1769 setattr(parser.values, option.dest, 1)
1783 a fixed number of arguments. Specifying that a callback option takes arguments
1784 is similar to defining a ``"store"`` or ``"append"`` option: if you define
1785 :attr:`~Option.type`, then the option takes one argument that must be
1786 convertible to that type; if you further define :attr:`~Option.nargs`, then the
1787 option takes :attr:`~Option.nargs` arguments.
1791 def store_value(option, opt_str, value, parser):
1792 setattr(parser.values, option.dest, value)
1808 Things get hairy when you want an option to take a variable number of arguments.
1815 * either ``--`` or ``-`` can be option arguments
1817 * bare ``--`` (if not the argument to some option): halt command-line
1820 * bare ``-`` (if not the argument to some option): halt command-line
1823 If you want an option that takes a variable number of arguments, there are
1829 Nevertheless, here's a stab at a callback for an option with variable
1832 def vararg_callback(option, opt_str, value, parser):
1853 setattr(parser.values, option.dest, value)
1866 command-line options are the action and type of each option, the most likely
1876 :class:`Option` class. This class has a couple of attributes that define
1877 :mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
1879 .. attribute:: Option.TYPES
1884 .. attribute:: Option.TYPE_CHECKER
1889 def check_mytype(option, opt, value)
1891 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1905 Here's a silly example that demonstrates adding a ``"complex"`` option type to
1913 from optparse import Option, OptionValueError
1916 :attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
1918 def check_complex(option, opt, value):
1923 "option %s: invalid complex value: %r" % (opt, value))
1925 Finally, the Option subclass::
1927 class MyOption (Option):
1928 TYPES = Option.TYPES + ("complex",)
1929 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1932 (If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1933 up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1934 Option class. This being Python, nothing stops you from doing that except good
1937 That's it! Now you can write a script that uses the new option type just like
1939 OptionParser to use MyOption instead of Option::
1944 Alternately, you can build your own option list and pass it to OptionParser; if
1946 OptionParser which option class to use::
1962 current OptionValues instance; these options require a :attr:`~Option.dest`
1963 attribute to be supplied to the Option constructor.
1968 These options require a :attr:`~Option.type` attribute to the Option
1976 of the following class attributes of Option (all are lists of strings):
1978 .. attribute:: Option.ACTIONS
1982 .. attribute:: Option.STORE_ACTIONS
1986 .. attribute:: Option.TYPED_ACTIONS
1990 .. attribute:: Option.ALWAYS_TYPED_ACTIONS
1997 In order to actually implement your new action, you must override Option's
2004 is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
2013 Again we define a subclass of Option::
2015 class MyOption(Option):
2017 ACTIONS = Option.ACTIONS + ("extend",)
2018 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
2019 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
2020 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
2027 Option.take_action(
2033 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
2034 :attr:`~Option.TYPED_ACTIONS`.
2038 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
2041 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
2056 about setting a default value for the option destinations in question; they
2065 Raised if an :class:`Option` instance is created with invalid or
2074 Raised if an invalid option value is encountered on the command line.
2078 Raised if an invalid option is passed on the command line.
2082 Raised if an ambiguous option is passed on the command line.