Lines Matching +full:- +full:- +full:option
1 :mod:`optparse` --- Parser for command line options
5 :synopsis: Command-line option parsing library.
18 --------------
21 command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
22 more declarative style of command-line parsing: you create an instance of
32 parser.add_option("-f", "--file", dest="filename",
34 parser.add_option("-q", "--quiet",
41 on the command-line, for example::
43 <yourscript> --file=outfile -q
46 ``options`` object returned by :meth:`parse_args` based on user-supplied
47 command-line values. When :meth:`parse_args` returns from parsing this command
54 <yourscript> -f outfile --quiet
55 <yourscript> --quiet --file outfile
56 <yourscript> -q -foutfile
57 <yourscript> -qfoutfile
61 <yourscript> -h
62 <yourscript> --help
66 .. code-block:: text
71 -h, --help show this help message and exit
72 -f FILE, --file=FILE write report to FILE
73 -q, --quiet don't print status messages to stdout
79 .. _optparse-background:
82 ----------
85 with straightforward, conventional command-line interfaces. To that end, it
86 supports only the most common command-line syntax and semantics conventionally
91 .. _optparse-terminology:
97 a string entered on the command-line, and passed by the shell to ``execl()``
107 option
110 traditional Unix syntax is a hyphen ("-") followed by a single letter,
111 e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple
112 options to be merged into a single argument, e.g. ``-x -F`` is equivalent
113 to ``-xF``. The GNU project introduced ``--`` followed by a series of
114 hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
115 only two option syntaxes provided by :mod:`optparse`.
117 Some other option syntaxes that the world has seen include:
119 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
122 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
132 These option syntaxes are not supported by :mod:`optparse`, and they never
133 will be. This is deliberate: the first three are non-standard on any
135 VMS, MS-DOS, and/or Windows.
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:
143 .. code-block:: text
145 -f foo
146 --file foo
150 .. code-block:: text
152 -ffoo
153 --file=foo
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
158 somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
159 an optional argument and ``-b`` is another option entirely, how do we
160 interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
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
174 For example, consider this hypothetical command-line::
176 prog -v --report report.txt foo bar
178 ``-v`` and ``--report`` are both options. Assuming that ``--report``
179 takes one argument, ``report.txt`` is an option argument. ``foo`` and
183 .. _optparse-what-options-for:
193 ``dd``\ ---all of which are mutant oddballs that have been rightly criticized
194 for their non-standard syntax and confusing interfaces.)
201 As an example of good command-line interface design, consider the humble ``cp``
208 cp SOURCE ... DEST-DIR
218 .. _optparse-what-positional-arguments-for:
229 user---most people will give up and walk away before they successfully run the
230 program. This applies whether the user interface is a command-line, a
235 required to supply---use sensible defaults whenever possible. Of course, you
238 the "Preferences" dialog of a GUI, or command-line options---the more options
244 .. _optparse-tutorial:
247 --------
251 any :mod:`optparse`\ -based program.
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
272 parser.add_option("-f", "--file", ...)
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.
294 * ``options``, an object containing values for all of your options---e.g. if
295 ``--file`` takes a single string argument, then ``options.file`` will be the
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
313 command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
315 :ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
316 a value in some variable---for example, take a string from the command line and
319 If you don't specify an option action, :mod:`optparse` defaults to ``store``.
322 .. _optparse-store-action:
327 The most common option action is ``store``, which tells :mod:`optparse` to take
333 parser.add_option("-f", "--file",
338 args = ["-f", "foo.txt"]
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::
348 parser.add_option("-n", type="int", dest="num")
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
355 ``-n 42`` (two arguments), the code ::
357 (options, args) = parser.parse_args(["-n42"])
366 parser.add_option("-f", "--file", dest="filename")
369 default from the option strings: if the first long option string is
370 ``--foo-bar``, then the default destination is ``foo_bar``. If there are no
371 long option strings, :mod:`optparse` looks at the first short option string: the
372 default destination for ``-f`` is ``f``.
374 :mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding
375 types is covered in section :ref:`optparse-extending-optparse`.
378 .. _optparse-handling-boolean-options:
383 Flag options---set a variable to true or false when a particular option is seen
384 ---are quite common. :mod:`optparse` supports them with two separate actions,
386 flag that is turned on with ``-v`` and off with ``-q``::
388 parser.add_option("-v", action="store_true", dest="verbose")
389 parser.add_option("-q", action="store_false", dest="verbose")
392 OK. (It just means you have to be a bit careful when setting default values---
395 When :mod:`optparse` encounters ``-v`` on the command line, it sets
396 ``options.verbose`` to ``True``; when it encounters ``-q``,
400 .. _optparse-other-actions:
411 append this option's argument to a list
419 These are covered in section :ref:`optparse-reference-guide`, Reference Guide
420 and section :ref:`optparse-option-callbacks`.
423 .. _optparse-default-values:
429 certain command-line options are seen. What happens if those options are never
436 ``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
438 parser.add_option("-v", action="store_true", dest="verbose", default=True)
439 parser.add_option("-q", action="store_false", dest="verbose")
442 option, and these two options happen to have the same destination, this is
445 parser.add_option("-v", action="store_true", dest="verbose")
446 parser.add_option("-q", action="store_false", dest="verbose", default=True)
450 parser.add_option("-v", action="store_true", dest="verbose", default=False)
451 parser.add_option("-q", action="store_false", dest="verbose", default=True)
463 As before, the last value specified for a given option destination is the one
468 .. _optparse-generating-help:
474 useful for creating user-friendly command-line interfaces. All you have to do
475 is supply a :attr:`~Option.help` value for each option, and optionally a short
477 user-friendly (documented) options::
481 parser.add_option("-v", "--verbose",
484 parser.add_option("-q", "--quiet",
487 parser.add_option("-f", "--filename",
489 parser.add_option("-m", "--mode",
494 If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
495 command-line, or if you just call :meth:`parser.print_help`, it prints the
498 .. code-block:: text
503 -h, --help show this help message and exit
504 -v, --verbose make lots of noise [default]
505 -q, --quiet be vewwy quiet (I'm hunting wabbits)
506 -f FILE, --filename=FILE
508 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
511 (If the help output is triggered by a help option, :mod:`optparse` exits after
523 is then printed before the detailed option help.
529 * every option defines a help string, and doesn't worry about line-wrapping---
533 * options that take a value indicate this fact in their automatically-generated
534 help message, e.g. for the "mode" option::
536 -m MODE, --mode=MODE
538 Here, "MODE" is called the meta-variable: it stands for the argument that the
539 user is expected to supply to ``-m``/``--mode``. By default,
541 that for the meta-variable. Sometimes, that's not what you want---for
542 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
543 resulting in this automatically-generated option description::
545 -f FILE, --filename=FILE
548 written help text uses the meta-variable ``FILE`` to clue the user in that
549 there's a connection between the semi-formal syntax ``-f FILE`` and the informal
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.")
595 .. code-block:: text
600 -h, --help show this help message and exit
601 -v, --verbose make lots of noise [default]
602 -q, --quiet be vewwy quiet (I'm hunting wabbits)
603 -f FILE, --filename=FILE
605 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
612 -g Group option.
620 group.add_option("-g", action="store_true", help="Group option.")
624 group.add_option("-d", "--debug", action="store_true",
626 group.add_option("-s", "--sql", action="store_true",
628 group.add_option("-e", action="store_true", help="Print every action done")
633 .. code-block:: text
638 -h, --help show this help message and exit
639 -v, --verbose make lots of noise [default]
640 -q, --quiet be vewwy quiet (I'm hunting wabbits)
641 -f FILE, --filename=FILE
643 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
650 -g Group option.
653 -d, --debug Print debug information
654 -s, --sql Print all SQL statements executed
655 -e Print every action done
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
666 .. _optparse-printing-version-string:
675 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
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
685 .. code-block:: shell-session
687 $ /usr/bin/foo --version
705 .. _optparse-how-optparse-handles-errors:
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
720 ``-n`` takes an integer argument), missing arguments (``-n`` at the end
721 of the command line, where ``-n`` takes an argument of any type). Also,
722 you can call :func:`OptionParser.error` to signal an application-defined error
728 parser.error("options -a and -b are mutually exclusive")
734 Consider the first example above, where the user passes ``4x`` to an option
737 .. code-block:: shell-session
739 $ /usr/bin/foo -n 4x
742 foo: error: option -n: invalid integer value: '4x'
746 .. code-block:: shell-session
748 $ /usr/bin/foo -n
751 foo: error: -n option requires an argument
753 :mod:`optparse`\ -generated error messages take care always to mention the
754 option involved in the error; be sure to do the same when calling
757 If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
762 .. _optparse-putting-it-all-together:
767 Here's what :mod:`optparse`\ -based scripts usually look like::
774 parser.add_option("-f", "--file", dest="filename",
776 parser.add_option("-v", "--verbose",
778 parser.add_option("-q", "--quiet",
792 .. _optparse-reference-guide:
795 ---------------
798 .. _optparse-creating-parser:
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
837 :ref:`optparse-conflicts-between-options`.
851 If true, :mod:`optparse` will add a help option (with option strings ``-h``
852 and ``--help``) to the parser.
859 A paragraph of help text to print after the option help.
861 .. _optparse-populating-parser:
868 :ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
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
880 make_option("-f", "--filename",
882 make_option("-q", "--quiet",
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.)
893 .. _optparse-defining-options:
898 Each Option instance represents a set of synonymous command-line option strings,
899 e.g. ``-f`` and ``--file``. You can specify any number of short or
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::
910 parser.add_option("-f", attr=value, ...)
912 And to define an option with only a long option string::
914 parser.add_option("--foo", attr=value, ...)
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)
939 append this option's argument to a list
954 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
955 attributes; see :ref:`optparse-standard-option-actions`.)
959 ``options`` (it happens to be an instance of :class:`optparse.Values`). Option
961 according to the :attr:`~Option.dest` (destination) option attribute.
973 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
975 and the command-line being parsed includes any of the following::
977 -ffoo
978 -f foo
979 --file=foo
980 --file foo
982 then :mod:`optparse`, on seeing this option, will do the equivalent of ::
986 The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
987 as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
991 .. _optparse-option-attributes:
993 Option attributes
996 The following option attributes may be passed as keyword arguments to
997 :meth:`OptionParser.add_option`. If you pass an option attribute that is not
998 relevant to a particular option, or fail to pass a required option attribute,
1001 .. attribute:: Option.action
1005 Determines :mod:`optparse`'s behaviour when this option is seen on the
1007 <optparse-standard-option-actions>`.
1009 .. attribute:: Option.type
1013 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1014 the available option types are documented :ref:`here
1015 <optparse-standard-option-types>`.
1017 .. attribute:: Option.dest
1019 (default: derived from option strings)
1021 If the option's action implies writing or modifying a value somewhere, this
1022 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1026 .. attribute:: Option.default
1028 The value to use for this option's destination if the option is not seen on
1031 .. attribute:: Option.nargs
1035 How many arguments of type :attr:`~Option.type` should be consumed when this
1036 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1037 :attr:`~Option.dest`.
1039 .. attribute:: Option.const
1043 .. attribute:: Option.choices
1048 .. attribute:: Option.callback
1050 For options with action ``"callback"``, the callable to call when this option
1051 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1054 .. attribute:: Option.callback_args
1055 Option.callback_kwargs
1060 .. attribute:: Option.help
1062 Help text to print for this option when listing all available options after
1063 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
1064 no help text is supplied, the option will be listed without help text. To
1065 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1067 .. attribute:: Option.metavar
1069 (default: derived from option strings)
1071 Stand-in for the option argument(s) to use when printing help text. See
1072 section :ref:`optparse-tutorial` for an example.
1075 .. _optparse-standard-option-actions:
1077 Standard option actions
1080 The various option actions all have slightly different requirements and effects.
1081 Most actions have several relevant option attributes which you may specify to
1083 must specify for any option using that action.
1085 * ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1086 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1088 The option must be followed by an argument, which is converted to a value
1089 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1090 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1091 command line; all will be converted according to :attr:`~Option.type` and
1092 stored to :attr:`~Option.dest` as a tuple. See the
1093 :ref:`optparse-standard-option-types` section.
1095 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1098 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
1100 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
1101 from the first long option string (e.g., ``--foo-bar`` implies
1102 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
1103 destination from the first short option string (e.g., ``-f`` implies ``f``).
1107 parser.add_option("-f")
1108 parser.add_option("-p", type="float", nargs=3, dest="point")
1112 -f foo.txt -p 1 -3.5 4 -fbar.txt
1117 options.point = (1.0, -3.5, 4.0)
1120 * ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1121 :attr:`~Option.dest`]
1123 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
1127 parser.add_option("-q", "--quiet",
1129 parser.add_option("-v", "--verbose",
1131 parser.add_option("--noisy",
1134 If ``--noisy`` is seen, :mod:`optparse` will set ::
1138 * ``"store_true"`` [relevant: :attr:`~Option.dest`]
1141 :attr:`~Option.dest`.
1143 * ``"store_false"`` [relevant: :attr:`~Option.dest`]
1149 parser.add_option("--clobber", action="store_true", dest="clobber")
1150 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1152 * ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1153 :attr:`~Option.nargs`, :attr:`~Option.choices`]
1155 The option must be followed by an argument, which is appended to the list in
1156 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1158 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1159 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1160 is appended to :attr:`~Option.dest`.
1162 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1167 parser.add_option("-t", "--tracks", action="append", type="int")
1169 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
1175 If, a little later on, ``--tracks=4`` is seen, it does::
1180 option. This means that any default value specified must have an ``append``
1181 method. It also means that if the default value is non-empty, the default
1182 elements will be present in the parsed value for the option, with any values
1185 >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
1186 >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
1190 * ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1191 :attr:`~Option.dest`]
1193 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1194 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1195 ``None``, and an empty list is automatically created the first time the option
1198 * ``"count"`` [relevant: :attr:`~Option.dest`]
1200 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1201 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1206 parser.add_option("-v", action="count", dest="verbosity")
1208 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
1214 Every subsequent occurrence of ``-v`` results in ::
1218 * ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1219 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1220 :attr:`~Option.callback_kwargs`]
1222 Call the function specified by :attr:`~Option.callback`, which is called as ::
1224 func(option, opt_str, value, parser, *args, **kwargs)
1226 See section :ref:`optparse-option-callbacks` for more detail.
1230 Prints a complete help message for all the options in the current option
1232 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1233 option.
1235 If no :attr:`~Option.help` string is supplied for an option, it will still be
1236 listed in the help message. To omit an option entirely, use the special value
1239 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1246 # usually, a help option is added automatically, but that can
1250 parser.add_option("-h", "--help", action="help")
1251 parser.add_option("-v", action="store_true", dest="verbose",
1253 parser.add_option("--file", dest="filename",
1255 parser.add_option("--secret", help=SUPPRESS_HELP)
1257 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
1261 .. code-block:: text
1266 -h, --help Show this help message and exit
1267 -v Be moderately verbose
1268 --file=FILENAME Input file to read data from
1279 :attr:`~Option.help` options, you will rarely create ``version`` options,
1283 .. _optparse-standard-option-types:
1285 Standard option types
1288 :mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
1290 option types, see section :ref:`optparse-extending-optparse`.
1293 the command line is stored in the destination (or passed to the callback) as-is.
1310 ``"float"`` and ``"complex"`` option arguments are converted directly with
1311 :func:`float` and :func:`complex`, with similar error-handling.
1314 :attr:`~Option.choices` option attribute (a sequence of strings) defines the
1315 set of allowed option arguments. :func:`optparse.check_choice` compares
1316 user-supplied option arguments against this master list and raises
1320 .. _optparse-parsing-arguments:
1336 an :class:`optparse.Values` object to store option arguments in (default: a
1337 new instance of :class:`Values`) -- if you give an existing object, the
1338 option defaults will not be initialized on it
1351 for every option argument stored to an option destination) and returned by
1355 OptionParser's :meth:`error` method with an appropriate end-user error message.
1357 traditional Unix exit status for command-line errors).
1360 .. _optparse-querying-manipulating-option-parser:
1362 Querying and manipulating your option parser
1365 The default behavior of the option parser can be customized slightly, and you
1366 can also poke around your option parser and see what's there. OptionParser
1371 Set parsing to stop on the first non-option. For example, if ``-a`` and
1372 ``-b`` are both simple options that take no arguments, :mod:`optparse`
1375 prog -a arg1 -b arg2
1379 prog -a -b arg1 arg2
1382 restores traditional Unix syntax, where option parsing stops with the first
1383 non-option argument.
1391 Set parsing to not stop on the first non-option, allowing interspersing
1396 Returns the Option instance with the option string *opt_str*, or ``None`` if
1397 no options have that option string.
1401 Return true if the OptionParser has an option with option string *opt_str*
1402 (e.g., ``-q`` or ``--verbose``).
1406 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1407 option is removed. If that option provided any other option strings, all of
1408 those option strings become invalid. If *opt_str* does not occur in any
1409 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
1412 .. _optparse-conflicts-between-options:
1417 If you're not careful, it's easy to define options with conflicting option
1420 parser.add_option("-n", "--dry-run", ...)
1422 parser.add_option("-n", "--noisy", ...)
1427 Every time you add an option, :mod:`optparse` checks for conflicts with existing
1428 options. If it finds any, it invokes the current conflict-handling mechanism.
1429 You can set the conflict-handling mechanism either in the constructor::
1440 assume option conflicts are a programming error and raise
1444 resolve option conflicts intelligently (see below)
1451 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1452 parser.add_option("-n", "--noisy", ..., help="be noisy")
1454 At this point, :mod:`optparse` detects that a previously-added option is already
1455 using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1456 it resolves the situation by removing ``-n`` from the earlier option's list of
1457 option strings. Now ``--dry-run`` is the only way for the user to activate
1458 that option. If the user asks for help, the help message will reflect that::
1461 --dry-run do no harm
1463 -n, --noisy be noisy
1465 It's possible to whittle away the option strings for a previously-added option
1466 until there are none left, and the user has no way of invoking that option from
1467 the command-line. In that case, :mod:`optparse` removes that option completely,
1471 parser.add_option("--dry-run", ..., help="new dry-run option")
1473 At this point, the original ``-n``/``--dry-run`` option is no longer
1478 -n, --noisy be noisy
1479 --dry-run new dry-run option
1482 .. _optparse-cleanup:
1491 long-running applications where large object graphs are reachable from your
1495 .. _optparse-other-methods:
1522 Set default values for several option destinations at once. Using
1528 parser.add_option("--advanced", action="store_const",
1531 parser.add_option("--novice", action="store_const",
1538 parser.add_option("--advanced", action="store_const",
1540 parser.add_option("--novice", action="store_const",
1544 .. _optparse-option-callbacks:
1546 Option Callbacks
1547 ----------------
1549 When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1550 needs, you have two choices: extend :mod:`optparse` or define a callback option.
1554 There are two steps to defining a callback option:
1556 * define the option itself using the ``"callback"`` action
1562 .. _optparse-defining-callback-option:
1564 Defining a callback option
1567 As always, the easiest way to define a callback option is by using the
1568 :meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1569 only option attribute you must specify is ``callback``, the function to call::
1571 parser.add_option("-c", action="callback", callback=my_callback)
1574 defined ``my_callback()`` when you create this callback option. In this simple
1575 case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
1576 which usually means that the option takes no arguments---the mere presence of
1577 ``-c`` on the command-line is all it needs to know. In some
1579 number of command-line arguments. This is where writing callbacks gets tricky;
1584 :attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1587 def my_callback(option, opt, value, parser):
1591 There are several other option attributes that you can supply when you define a
1592 callback option:
1594 :attr:`~Option.type`
1597 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1600 :attr:`~Option.nargs`
1602 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1603 :attr:`~Option.type`. It then passes a tuple of converted values to your
1606 :attr:`~Option.callback_args`
1609 :attr:`~Option.callback_kwargs`
1613 .. _optparse-how-callbacks-called:
1620 func(option, opt_str, value, parser, *args, **kwargs)
1624 ``option``
1625 is the Option instance that's calling the callback
1628 is the option string seen on the command-line that's triggering the callback.
1629 (If an abbreviated long option was used, ``opt_str`` will be the full,
1630 canonical option string---e.g. if the user puts ``--foo`` on the
1631 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
1632 ``"--foobar"``.)
1635 is the argument to this option seen on the command-line. :mod:`optparse` will
1636 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1637 the type implied by the option's type. If :attr:`~Option.type` for this option is
1638 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
1647 consumed but are neither options nor option arguments. Feel free to modify
1658 the object where option values are by default stored (an instance of
1660 rest of :mod:`optparse` for storing option values; you don't need to mess
1662 value(s) of any options already encountered on the command-line.
1666 :attr:`~Option.callback_args` option attribute.
1670 :attr:`~Option.callback_kwargs`.
1673 .. _optparse-raising-errors-in-callback:
1679 problems with the option or its argument(s). :mod:`optparse` catches this and
1681 message should be clear, concise, accurate, and mention the option at fault.
1685 .. _optparse-callback-example-1:
1690 Here's an example of a callback option that takes no arguments, and simply
1691 records that the option was seen::
1693 def record_foo_seen(option, opt_str, value, parser):
1696 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1701 .. _optparse-callback-example-2:
1703 Callback example 2: check option order
1706 Here's a slightly more interesting example: record the fact that ``-a`` is
1707 seen, but blow up if it comes after ``-b`` in the command-line. ::
1709 def check_order(option, opt_str, value, parser):
1711 raise OptionValueError("can't use -a after -b")
1714 parser.add_option("-a", action="callback", callback=check_order)
1715 parser.add_option("-b", action="store_true", dest="b")
1718 .. _optparse-callback-example-3:
1720 Callback example 3: check option order (generalized)
1723 If you want to re-use this callback for several similar options (set a flag, but
1724 blow up if ``-b`` has already been seen), it needs a bit of work: the error
1727 def check_order(option, opt_str, value, parser):
1729 raise OptionValueError("can't use %s after -b" % opt_str)
1730 setattr(parser.values, option.dest, 1)
1732 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1733 parser.add_option("-b", action="store_true", dest="b")
1734 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1737 .. _optparse-callback-example-4:
1742 Of course, you could put any condition in there---you're not limited to checking
1743 the values of already-defined options. For example, if you have options that
1746 def check_moon(option, opt_str, value, parser):
1748 raise OptionValueError("%s option invalid when moon is full"
1750 setattr(parser.values, option.dest, 1)
1752 parser.add_option("--foo",
1758 .. _optparse-callback-example-5:
1764 a fixed number of arguments. Specifying that a callback option takes arguments
1765 is similar to defining a ``"store"`` or ``"append"`` option: if you define
1766 :attr:`~Option.type`, then the option takes one argument that must be
1767 convertible to that type; if you further define :attr:`~Option.nargs`, then the
1768 option takes :attr:`~Option.nargs` arguments.
1772 def store_value(option, opt_str, value, parser):
1773 setattr(parser.values, option.dest, value)
1775 parser.add_option("--foo",
1784 .. _optparse-callback-example-6:
1789 Things get hairy when you want an option to take a variable number of arguments.
1791 built-in capabilities for it. And you have to deal with certain intricacies of
1792 conventional Unix command-line parsing that :mod:`optparse` normally handles for
1794 ``--`` and ``-`` arguments:
1796 * either ``--`` or ``-`` can be option arguments
1798 * bare ``--`` (if not the argument to some option): halt command-line
1799 processing and discard the ``--``
1801 * bare ``-`` (if not the argument to some option): halt command-line
1802 processing but keep the ``-`` (append it to ``parser.largs``)
1804 If you want an option that takes a variable number of arguments, there are
1806 choose will be based on which trade-offs you're willing to make for your
1810 Nevertheless, here's a stab at a callback for an option with variable
1813 def vararg_callback(option, opt_str, value, parser):
1825 # stop on --foo like options
1826 if arg[:2] == "--" and len(arg) > 2:
1828 # stop on -a, but not on -3 or -3.0
1829 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1834 setattr(parser.values, option.dest, value)
1837 parser.add_option("-c", "--callback", dest="vararg_attr",
1841 .. _optparse-extending-optparse:
1844 -------------------------
1847 command-line options are the action and type of each option, the most likely
1851 .. _optparse-adding-new-types:
1857 :class:`Option` class. This class has a couple of attributes that define
1858 :mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
1860 .. attribute:: Option.TYPES
1865 .. attribute:: Option.TYPE_CHECKER
1867 A dictionary mapping type names to type-checking functions. A type-checking
1870 def check_mytype(option, opt, value)
1872 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1873 (e.g., ``-f``), and ``value`` is the string from the command line that must
1876 a type-checking function will wind up in the OptionValues instance returned
1880 Your type-checking function should raise :exc:`OptionValueError` if it
1882 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1886 Here's a silly example that demonstrates adding a ``"complex"`` option type to
1887 parse Python-style complex numbers on the command line. (This is even sillier
1888 than it used to be, because :mod:`optparse` 1.3 added built-in support for
1894 from optparse import Option, OptionValueError
1896 You need to define your type-checker first, since it's referred to later (in the
1897 :attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
1899 def check_complex(option, opt, value):
1904 "option %s: invalid complex value: %r" % (opt, value))
1906 Finally, the Option subclass::
1908 class MyOption (Option):
1909 TYPES = Option.TYPES + ("complex",)
1910 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1913 (If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1914 up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1915 Option class. This being Python, nothing stops you from doing that except good
1918 That's it! Now you can write a script that uses the new option type just like
1919 any other :mod:`optparse`\ -based script, except you have to instruct your
1920 OptionParser to use MyOption instead of Option::
1923 parser.add_option("-c", type="complex")
1925 Alternately, you can build your own option list and pass it to OptionParser; if
1927 OptionParser which option class to use::
1929 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1933 .. _optparse-adding-new-actions:
1943 current OptionValues instance; these options require a :attr:`~Option.dest`
1944 attribute to be supplied to the Option constructor.
1949 These options require a :attr:`~Option.type` attribute to the Option
1957 of the following class attributes of Option (all are lists of strings):
1959 .. attribute:: Option.ACTIONS
1963 .. attribute:: Option.STORE_ACTIONS
1967 .. attribute:: Option.TYPED_ACTIONS
1971 .. attribute:: Option.ALWAYS_TYPED_ACTIONS
1978 In order to actually implement your new action, you must override Option's
1982 ``"append"`` action, but instead of taking a single value from the command-line
1984 a single comma-delimited string, and extend an existing list with them. That
1985 is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
1988 --names=foo,bar --names blah --names ding,dong
1994 Again we define a subclass of Option::
1996 class MyOption(Option):
1998 ACTIONS = Option.ACTIONS + ("extend",)
1999 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
2000 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
2001 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
2008 Option.take_action(
2013 * ``"extend"`` both expects a value on the command-line and stores that value
2014 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
2015 :attr:`~Option.TYPED_ACTIONS`.
2019 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
2022 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
2037 about setting a default value for the option destinations in question; they