PageRenderTime 62ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/library/optparse.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 1901 lines | 1329 code | 572 blank | 0 comment | 0 complexity | a6c36a60dbbd380640ea5143f1d14569 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. :mod:`optparse` --- More powerful command line option parser
  2. ============================================================
  3. .. module:: optparse
  4. :synopsis: More convenient, flexible, and powerful command-line parsing library.
  5. .. moduleauthor:: Greg Ward <gward@python.net>
  6. .. versionadded:: 2.3
  7. .. sectionauthor:: Greg Ward <gward@python.net>
  8. :mod:`optparse` is a more convenient, flexible, and powerful library for parsing
  9. command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
  10. more declarative style of command-line parsing: you create an instance of
  11. :class:`OptionParser`, populate it with options, and parse the command
  12. line. :mod:`optparse` allows users to specify options in the conventional
  13. GNU/POSIX syntax, and additionally generates usage and help messages for you.
  14. Here's an example of using :mod:`optparse` in a simple script::
  15. from optparse import OptionParser
  16. [...]
  17. parser = OptionParser()
  18. parser.add_option("-f", "--file", dest="filename",
  19. help="write report to FILE", metavar="FILE")
  20. parser.add_option("-q", "--quiet",
  21. action="store_false", dest="verbose", default=True,
  22. help="don't print status messages to stdout")
  23. (options, args) = parser.parse_args()
  24. With these few lines of code, users of your script can now do the "usual thing"
  25. on the command-line, for example::
  26. <yourscript> --file=outfile -q
  27. As it parses the command line, :mod:`optparse` sets attributes of the
  28. ``options`` object returned by :meth:`parse_args` based on user-supplied
  29. command-line values. When :meth:`parse_args` returns from parsing this command
  30. line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
  31. ``False``. :mod:`optparse` supports both long and short options, allows short
  32. options to be merged together, and allows options to be associated with their
  33. arguments in a variety of ways. Thus, the following command lines are all
  34. equivalent to the above example::
  35. <yourscript> -f outfile --quiet
  36. <yourscript> --quiet --file outfile
  37. <yourscript> -q -foutfile
  38. <yourscript> -qfoutfile
  39. Additionally, users can run one of ::
  40. <yourscript> -h
  41. <yourscript> --help
  42. and :mod:`optparse` will print out a brief summary of your script's options::
  43. usage: <yourscript> [options]
  44. options:
  45. -h, --help show this help message and exit
  46. -f FILE, --file=FILE write report to FILE
  47. -q, --quiet don't print status messages to stdout
  48. where the value of *yourscript* is determined at runtime (normally from
  49. ``sys.argv[0]``).
  50. .. _optparse-background:
  51. Background
  52. ----------
  53. :mod:`optparse` was explicitly designed to encourage the creation of programs
  54. with straightforward, conventional command-line interfaces. To that end, it
  55. supports only the most common command-line syntax and semantics conventionally
  56. used under Unix. If you are unfamiliar with these conventions, read this
  57. section to acquaint yourself with them.
  58. .. _optparse-terminology:
  59. Terminology
  60. ^^^^^^^^^^^
  61. argument
  62. a string entered on the command-line, and passed by the shell to ``execl()``
  63. or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
  64. (``sys.argv[0]`` is the name of the program being executed). Unix shells
  65. also use the term "word".
  66. It is occasionally desirable to substitute an argument list other than
  67. ``sys.argv[1:]``, so you should read "argument" as "an element of
  68. ``sys.argv[1:]``, or of some other list provided as a substitute for
  69. ``sys.argv[1:]``".
  70. option
  71. an argument used to supply extra information to guide or customize the
  72. execution of a program. There are many different syntaxes for options; the
  73. traditional Unix syntax is a hyphen ("-") followed by a single letter,
  74. e.g. ``"-x"`` or ``"-F"``. Also, traditional Unix syntax allows multiple
  75. options to be merged into a single argument, e.g. ``"-x -F"`` is equivalent
  76. to ``"-xF"``. The GNU project introduced ``"--"`` followed by a series of
  77. hyphen-separated words, e.g. ``"--file"`` or ``"--dry-run"``. These are the
  78. only two option syntaxes provided by :mod:`optparse`.
  79. Some other option syntaxes that the world has seen include:
  80. * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
  81. as multiple options merged into a single argument)
  82. * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
  83. equivalent to the previous syntax, but they aren't usually seen in the same
  84. program)
  85. * a plus sign followed by a single letter, or a few letters, or a word, e.g.
  86. ``"+f"``, ``"+rgb"``
  87. * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
  88. ``"/file"``
  89. These option syntaxes are not supported by :mod:`optparse`, and they never
  90. will be. This is deliberate: the first three are non-standard on any
  91. environment, and the last only makes sense if you're exclusively targeting
  92. VMS, MS-DOS, and/or Windows.
  93. option argument
  94. an argument that follows an option, is closely associated with that option,
  95. and is consumed from the argument list when that option is. With
  96. :mod:`optparse`, option arguments may either be in a separate argument from
  97. their option::
  98. -f foo
  99. --file foo
  100. or included in the same argument::
  101. -ffoo
  102. --file=foo
  103. Typically, a given option either takes an argument or it doesn't. Lots of
  104. people want an "optional option arguments" feature, meaning that some options
  105. will take an argument if they see it, and won't if they don't. This is
  106. somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes
  107. an optional argument and ``"-b"`` is another option entirely, how do we
  108. interpret ``"-ab"``? Because of this ambiguity, :mod:`optparse` does not
  109. support this feature.
  110. positional argument
  111. something leftover in the argument list after options have been parsed, i.e.
  112. after options and their arguments have been parsed and removed from the
  113. argument list.
  114. required option
  115. an option that must be supplied on the command-line; note that the phrase
  116. "required option" is self-contradictory in English. :mod:`optparse` doesn't
  117. prevent you from implementing required options, but doesn't give you much
  118. help at it either. See ``examples/required_1.py`` and
  119. ``examples/required_2.py`` in the :mod:`optparse` source distribution for two
  120. ways to implement required options with :mod:`optparse`.
  121. For example, consider this hypothetical command-line::
  122. prog -v --report /tmp/report.txt foo bar
  123. ``"-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`
  124. takes one argument, ``"/tmp/report.txt"`` is an option argument. ``"foo"`` and
  125. ``"bar"`` are positional arguments.
  126. .. _optparse-what-options-for:
  127. What are options for?
  128. ^^^^^^^^^^^^^^^^^^^^^
  129. Options are used to provide extra information to tune or customize the execution
  130. of a program. In case it wasn't clear, options are usually *optional*. A
  131. program should be able to run just fine with no options whatsoever. (Pick a
  132. random program from the Unix or GNU toolsets. Can it run without any options at
  133. all and still make sense? The main exceptions are ``find``, ``tar``, and
  134. ``dd``\ ---all of which are mutant oddballs that have been rightly criticized
  135. for their non-standard syntax and confusing interfaces.)
  136. Lots of people want their programs to have "required options". Think about it.
  137. If it's required, then it's *not optional*! If there is a piece of information
  138. that your program absolutely requires in order to run successfully, that's what
  139. positional arguments are for.
  140. As an example of good command-line interface design, consider the humble ``cp``
  141. utility, for copying files. It doesn't make much sense to try to copy files
  142. without supplying a destination and at least one source. Hence, ``cp`` fails if
  143. you run it with no arguments. However, it has a flexible, useful syntax that
  144. does not require any options at all::
  145. cp SOURCE DEST
  146. cp SOURCE ... DEST-DIR
  147. You can get pretty far with just that. Most ``cp`` implementations provide a
  148. bunch of options to tweak exactly how the files are copied: you can preserve
  149. mode and modification time, avoid following symlinks, ask before clobbering
  150. existing files, etc. But none of this distracts from the core mission of
  151. ``cp``, which is to copy either one file to another, or several files to another
  152. directory.
  153. .. _optparse-what-positional-arguments-for:
  154. What are positional arguments for?
  155. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  156. Positional arguments are for those pieces of information that your program
  157. absolutely, positively requires to run.
  158. A good user interface should have as few absolute requirements as possible. If
  159. your program requires 17 distinct pieces of information in order to run
  160. successfully, it doesn't much matter *how* you get that information from the
  161. user---most people will give up and walk away before they successfully run the
  162. program. This applies whether the user interface is a command-line, a
  163. configuration file, or a GUI: if you make that many demands on your users, most
  164. of them will simply give up.
  165. In short, try to minimize the amount of information that users are absolutely
  166. required to supply---use sensible defaults whenever possible. Of course, you
  167. also want to make your programs reasonably flexible. That's what options are
  168. for. Again, it doesn't matter if they are entries in a config file, widgets in
  169. the "Preferences" dialog of a GUI, or command-line options---the more options
  170. you implement, the more flexible your program is, and the more complicated its
  171. implementation becomes. Too much flexibility has drawbacks as well, of course;
  172. too many options can overwhelm users and make your code much harder to maintain.
  173. .. _optparse-tutorial:
  174. Tutorial
  175. --------
  176. While :mod:`optparse` is quite flexible and powerful, it's also straightforward
  177. to use in most cases. This section covers the code patterns that are common to
  178. any :mod:`optparse`\ -based program.
  179. First, you need to import the OptionParser class; then, early in the main
  180. program, create an OptionParser instance::
  181. from optparse import OptionParser
  182. [...]
  183. parser = OptionParser()
  184. Then you can start defining options. The basic syntax is::
  185. parser.add_option(opt_str, ...,
  186. attr=value, ...)
  187. Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
  188. and several option attributes that tell :mod:`optparse` what to expect and what
  189. to do when it encounters that option on the command line.
  190. Typically, each option will have one short option string and one long option
  191. string, e.g.::
  192. parser.add_option("-f", "--file", ...)
  193. You're free to define as many short option strings and as many long option
  194. strings as you like (including zero), as long as there is at least one option
  195. string overall.
  196. The option strings passed to :meth:`add_option` are effectively labels for the
  197. option defined by that call. For brevity, we will frequently refer to
  198. *encountering an option* on the command line; in reality, :mod:`optparse`
  199. encounters *option strings* and looks up options from them.
  200. Once all of your options are defined, instruct :mod:`optparse` to parse your
  201. program's command line::
  202. (options, args) = parser.parse_args()
  203. (If you like, you can pass a custom argument list to :meth:`parse_args`, but
  204. that's rarely necessary: by default it uses ``sys.argv[1:]``.)
  205. :meth:`parse_args` returns two values:
  206. * ``options``, an object containing values for all of your options---e.g. if
  207. ``"--file"`` takes a single string argument, then ``options.file`` will be the
  208. filename supplied by the user, or ``None`` if the user did not supply that
  209. option
  210. * ``args``, the list of positional arguments leftover after parsing options
  211. This tutorial section only covers the four most important option attributes:
  212. :attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
  213. (destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
  214. most fundamental.
  215. .. _optparse-understanding-option-actions:
  216. Understanding option actions
  217. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  218. Actions tell :mod:`optparse` what to do when it encounters an option on the
  219. command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
  220. adding new actions is an advanced topic covered in section
  221. :ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
  222. a value in some variable---for example, take a string from the command line and
  223. store it in an attribute of ``options``.
  224. If you don't specify an option action, :mod:`optparse` defaults to ``store``.
  225. .. _optparse-store-action:
  226. The store action
  227. ^^^^^^^^^^^^^^^^
  228. The most common option action is ``store``, which tells :mod:`optparse` to take
  229. the next argument (or the remainder of the current argument), ensure that it is
  230. of the correct type, and store it to your chosen destination.
  231. For example::
  232. parser.add_option("-f", "--file",
  233. action="store", type="string", dest="filename")
  234. Now let's make up a fake command line and ask :mod:`optparse` to parse it::
  235. args = ["-f", "foo.txt"]
  236. (options, args) = parser.parse_args(args)
  237. When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
  238. argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
  239. call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
  240. Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
  241. Here's an option that expects an integer argument::
  242. parser.add_option("-n", type="int", dest="num")
  243. Note that this option has no long option string, which is perfectly acceptable.
  244. Also, there's no explicit action, since the default is ``store``.
  245. Let's parse another fake command-line. This time, we'll jam the option argument
  246. right up against the option: since ``"-n42"`` (one argument) is equivalent to
  247. ``"-n 42"`` (two arguments), the code ::
  248. (options, args) = parser.parse_args(["-n42"])
  249. print options.num
  250. will print ``"42"``.
  251. If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
  252. the fact that the default action is ``store``, that means our first example can
  253. be a lot shorter::
  254. parser.add_option("-f", "--file", dest="filename")
  255. If you don't supply a destination, :mod:`optparse` figures out a sensible
  256. default from the option strings: if the first long option string is
  257. ``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
  258. long option strings, :mod:`optparse` looks at the first short option string: the
  259. default destination for ``"-f"`` is ``f``.
  260. :mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding
  261. types is covered in section :ref:`optparse-extending-optparse`.
  262. .. _optparse-handling-boolean-options:
  263. Handling boolean (flag) options
  264. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  265. Flag options---set a variable to true or false when a particular option is seen
  266. ---are quite common. :mod:`optparse` supports them with two separate actions,
  267. ``store_true`` and ``store_false``. For example, you might have a ``verbose``
  268. flag that is turned on with ``"-v"`` and off with ``"-q"``::
  269. parser.add_option("-v", action="store_true", dest="verbose")
  270. parser.add_option("-q", action="store_false", dest="verbose")
  271. Here we have two different options with the same destination, which is perfectly
  272. OK. (It just means you have to be a bit careful when setting default values---
  273. see below.)
  274. When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
  275. ``options.verbose`` to ``True``; when it encounters ``"-q"``,
  276. ``options.verbose`` is set to ``False``.
  277. .. _optparse-other-actions:
  278. Other actions
  279. ^^^^^^^^^^^^^
  280. Some other actions supported by :mod:`optparse` are:
  281. ``"store_const"``
  282. store a constant value
  283. ``"append"``
  284. append this option's argument to a list
  285. ``"count"``
  286. increment a counter by one
  287. ``"callback"``
  288. call a specified function
  289. These are covered in section :ref:`optparse-reference-guide`, Reference Guide
  290. and section :ref:`optparse-option-callbacks`.
  291. .. _optparse-default-values:
  292. Default values
  293. ^^^^^^^^^^^^^^
  294. All of the above examples involve setting some variable (the "destination") when
  295. certain command-line options are seen. What happens if those options are never
  296. seen? Since we didn't supply any defaults, they are all set to ``None``. This
  297. is usually fine, but sometimes you want more control. :mod:`optparse` lets you
  298. supply a default value for each destination, which is assigned before the
  299. command line is parsed.
  300. First, consider the verbose/quiet example. If we want :mod:`optparse` to set
  301. ``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
  302. parser.add_option("-v", action="store_true", dest="verbose", default=True)
  303. parser.add_option("-q", action="store_false", dest="verbose")
  304. Since default values apply to the *destination* rather than to any particular
  305. option, and these two options happen to have the same destination, this is
  306. exactly equivalent::
  307. parser.add_option("-v", action="store_true", dest="verbose")
  308. parser.add_option("-q", action="store_false", dest="verbose", default=True)
  309. Consider this::
  310. parser.add_option("-v", action="store_true", dest="verbose", default=False)
  311. parser.add_option("-q", action="store_false", dest="verbose", default=True)
  312. Again, the default value for ``verbose`` will be ``True``: the last default
  313. value supplied for any particular destination is the one that counts.
  314. A clearer way to specify default values is the :meth:`set_defaults` method of
  315. OptionParser, which you can call at any time before calling :meth:`parse_args`::
  316. parser.set_defaults(verbose=True)
  317. parser.add_option(...)
  318. (options, args) = parser.parse_args()
  319. As before, the last value specified for a given option destination is the one
  320. that counts. For clarity, try to use one method or the other of setting default
  321. values, not both.
  322. .. _optparse-generating-help:
  323. Generating help
  324. ^^^^^^^^^^^^^^^
  325. :mod:`optparse`'s ability to generate help and usage text automatically is
  326. useful for creating user-friendly command-line interfaces. All you have to do
  327. is supply a :attr:`~Option.help` value for each option, and optionally a short
  328. usage message for your whole program. Here's an OptionParser populated with
  329. user-friendly (documented) options::
  330. usage = "usage: %prog [options] arg1 arg2"
  331. parser = OptionParser(usage=usage)
  332. parser.add_option("-v", "--verbose",
  333. action="store_true", dest="verbose", default=True,
  334. help="make lots of noise [default]")
  335. parser.add_option("-q", "--quiet",
  336. action="store_false", dest="verbose",
  337. help="be vewwy quiet (I'm hunting wabbits)")
  338. parser.add_option("-f", "--filename",
  339. metavar="FILE", help="write output to FILE")
  340. parser.add_option("-m", "--mode",
  341. default="intermediate",
  342. help="interaction mode: novice, intermediate, "
  343. "or expert [default: %default]")
  344. If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
  345. command-line, or if you just call :meth:`parser.print_help`, it prints the
  346. following to standard output::
  347. usage: <yourscript> [options] arg1 arg2
  348. options:
  349. -h, --help show this help message and exit
  350. -v, --verbose make lots of noise [default]
  351. -q, --quiet be vewwy quiet (I'm hunting wabbits)
  352. -f FILE, --filename=FILE
  353. write output to FILE
  354. -m MODE, --mode=MODE interaction mode: novice, intermediate, or
  355. expert [default: intermediate]
  356. (If the help output is triggered by a help option, :mod:`optparse` exits after
  357. printing the help text.)
  358. There's a lot going on here to help :mod:`optparse` generate the best possible
  359. help message:
  360. * the script defines its own usage message::
  361. usage = "usage: %prog [options] arg1 arg2"
  362. :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
  363. current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
  364. is then printed before the detailed option help.
  365. If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
  366. default: ``"usage: %prog [options]"``, which is fine if your script doesn't
  367. take any positional arguments.
  368. * every option defines a help string, and doesn't worry about line-wrapping---
  369. :mod:`optparse` takes care of wrapping lines and making the help output look
  370. good.
  371. * options that take a value indicate this fact in their automatically-generated
  372. help message, e.g. for the "mode" option::
  373. -m MODE, --mode=MODE
  374. Here, "MODE" is called the meta-variable: it stands for the argument that the
  375. user is expected to supply to :option:`-m`/:option:`--mode`. By default,
  376. :mod:`optparse` converts the destination variable name to uppercase and uses
  377. that for the meta-variable. Sometimes, that's not what you want---for
  378. example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
  379. resulting in this automatically-generated option description::
  380. -f FILE, --filename=FILE
  381. This is important for more than just saving space, though: the manually
  382. written help text uses the meta-variable "FILE" to clue the user in that
  383. there's a connection between the semi-formal syntax "-f FILE" and the informal
  384. semantic description "write output to FILE". This is a simple but effective
  385. way to make your help text a lot clearer and more useful for end users.
  386. .. versionadded:: 2.4
  387. Options that have a default value can include ``%default`` in the help
  388. string---\ :mod:`optparse` will replace it with :func:`str` of the option's
  389. default value. If an option has no default value (or the default value is
  390. ``None``), ``%default`` expands to ``none``.
  391. When dealing with many options, it is convenient to group these options for
  392. better help output. An :class:`OptionParser` can contain several option groups,
  393. each of which can contain several options.
  394. Continuing with the parser defined above, adding an :class:`OptionGroup` to a
  395. parser is easy::
  396. group = OptionGroup(parser, "Dangerous Options",
  397. "Caution: use these options at your own risk. "
  398. "It is believed that some of them bite.")
  399. group.add_option("-g", action="store_true", help="Group option.")
  400. parser.add_option_group(group)
  401. This would result in the following help output::
  402. usage: [options] arg1 arg2
  403. options:
  404. -h, --help show this help message and exit
  405. -v, --verbose make lots of noise [default]
  406. -q, --quiet be vewwy quiet (I'm hunting wabbits)
  407. -fFILE, --file=FILE write output to FILE
  408. -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
  409. [default], 'expert'
  410. Dangerous Options:
  411. Caution: use of these options is at your own risk. It is believed that
  412. some of them bite.
  413. -g Group option.
  414. .. _optparse-printing-version-string:
  415. Printing a version string
  416. ^^^^^^^^^^^^^^^^^^^^^^^^^
  417. Similar to the brief usage string, :mod:`optparse` can also print a version
  418. string for your program. You have to supply the string as the ``version``
  419. argument to OptionParser::
  420. parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
  421. ``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
  422. ``version`` can contain anything you like. When you supply it, :mod:`optparse`
  423. automatically adds a ``"--version"`` option to your parser. If it encounters
  424. this option on the command line, it expands your ``version`` string (by
  425. replacing ``"%prog"``), prints it to stdout, and exits.
  426. For example, if your script is called ``/usr/bin/foo``::
  427. $ /usr/bin/foo --version
  428. foo 1.0
  429. .. _optparse-how-optparse-handles-errors:
  430. How :mod:`optparse` handles errors
  431. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  432. There are two broad classes of errors that :mod:`optparse` has to worry about:
  433. programmer errors and user errors. Programmer errors are usually erroneous
  434. calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
  435. option attributes, missing option attributes, etc. These are dealt with in the
  436. usual way: raise an exception (either :exc:`optparse.OptionError` or
  437. :exc:`TypeError`) and let the program crash.
  438. Handling user errors is much more important, since they are guaranteed to happen
  439. no matter how stable your code is. :mod:`optparse` can automatically detect
  440. some user errors, such as bad option arguments (passing ``"-n 4x"`` where
  441. :option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
  442. of the command line, where :option:`-n` takes an argument of any type). Also,
  443. you can call :func:`OptionParser.error` to signal an application-defined error
  444. condition::
  445. (options, args) = parser.parse_args()
  446. [...]
  447. if options.a and options.b:
  448. parser.error("options -a and -b are mutually exclusive")
  449. In either case, :mod:`optparse` handles the error the same way: it prints the
  450. program's usage message and an error message to standard error and exits with
  451. error status 2.
  452. Consider the first example above, where the user passes ``"4x"`` to an option
  453. that takes an integer::
  454. $ /usr/bin/foo -n 4x
  455. usage: foo [options]
  456. foo: error: option -n: invalid integer value: '4x'
  457. Or, where the user fails to pass a value at all::
  458. $ /usr/bin/foo -n
  459. usage: foo [options]
  460. foo: error: -n option requires an argument
  461. :mod:`optparse`\ -generated error messages take care always to mention the
  462. option involved in the error; be sure to do the same when calling
  463. :func:`OptionParser.error` from your application code.
  464. If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
  465. you'll need to subclass OptionParser and override its :meth:`exit` and/or
  466. :meth:`error` methods.
  467. .. _optparse-putting-it-all-together:
  468. Putting it all together
  469. ^^^^^^^^^^^^^^^^^^^^^^^
  470. Here's what :mod:`optparse`\ -based scripts usually look like::
  471. from optparse import OptionParser
  472. [...]
  473. def main():
  474. usage = "usage: %prog [options] arg"
  475. parser = OptionParser(usage)
  476. parser.add_option("-f", "--file", dest="filename",
  477. help="read data from FILENAME")
  478. parser.add_option("-v", "--verbose",
  479. action="store_true", dest="verbose")
  480. parser.add_option("-q", "--quiet",
  481. action="store_false", dest="verbose")
  482. [...]
  483. (options, args) = parser.parse_args()
  484. if len(args) != 1:
  485. parser.error("incorrect number of arguments")
  486. if options.verbose:
  487. print "reading %s..." % options.filename
  488. [...]
  489. if __name__ == "__main__":
  490. main()
  491. .. _optparse-reference-guide:
  492. Reference Guide
  493. ---------------
  494. .. _optparse-creating-parser:
  495. Creating the parser
  496. ^^^^^^^^^^^^^^^^^^^
  497. The first step in using :mod:`optparse` is to create an OptionParser instance.
  498. .. class:: OptionParser(...)
  499. The OptionParser constructor has no required arguments, but a number of
  500. optional keyword arguments. You should always pass them as keyword
  501. arguments, i.e. do not rely on the order in which the arguments are declared.
  502. ``usage`` (default: ``"%prog [options]"``)
  503. The usage summary to print when your program is run incorrectly or with a
  504. help option. When :mod:`optparse` prints the usage string, it expands
  505. ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
  506. passed that keyword argument). To suppress a usage message, pass the
  507. special value :data:`optparse.SUPPRESS_USAGE`.
  508. ``option_list`` (default: ``[]``)
  509. A list of Option objects to populate the parser with. The options in
  510. ``option_list`` are added after any options in ``standard_option_list`` (a
  511. class attribute that may be set by OptionParser subclasses), but before
  512. any version or help options. Deprecated; use :meth:`add_option` after
  513. creating the parser instead.
  514. ``option_class`` (default: optparse.Option)
  515. Class to use when adding options to the parser in :meth:`add_option`.
  516. ``version`` (default: ``None``)
  517. A version string to print when the user supplies a version option. If you
  518. supply a true value for ``version``, :mod:`optparse` automatically adds a
  519. version option with the single option string ``"--version"``. The
  520. substring ``"%prog"`` is expanded the same as for ``usage``.
  521. ``conflict_handler`` (default: ``"error"``)
  522. Specifies what to do when options with conflicting option strings are
  523. added to the parser; see section
  524. :ref:`optparse-conflicts-between-options`.
  525. ``description`` (default: ``None``)
  526. A paragraph of text giving a brief overview of your program.
  527. :mod:`optparse` reformats this paragraph to fit the current terminal width
  528. and prints it when the user requests help (after ``usage``, but before the
  529. list of options).
  530. ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
  531. An instance of optparse.HelpFormatter that will be used for printing help
  532. text. :mod:`optparse` provides two concrete classes for this purpose:
  533. IndentedHelpFormatter and TitledHelpFormatter.
  534. ``add_help_option`` (default: ``True``)
  535. If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
  536. and ``"--help"``) to the parser.
  537. ``prog``
  538. The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
  539. instead of ``os.path.basename(sys.argv[0])``.
  540. .. _optparse-populating-parser:
  541. Populating the parser
  542. ^^^^^^^^^^^^^^^^^^^^^
  543. There are several ways to populate the parser with options. The preferred way
  544. is by using :meth:`OptionParser.add_option`, as shown in section
  545. :ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
  546. * pass it an Option instance (as returned by :func:`make_option`)
  547. * pass it any combination of positional and keyword arguments that are
  548. acceptable to :func:`make_option` (i.e., to the Option constructor), and it
  549. will create the Option instance for you
  550. The other alternative is to pass a list of pre-constructed Option instances to
  551. the OptionParser constructor, as in::
  552. option_list = [
  553. make_option("-f", "--filename",
  554. action="store", type="string", dest="filename"),
  555. make_option("-q", "--quiet",
  556. action="store_false", dest="verbose"),
  557. ]
  558. parser = OptionParser(option_list=option_list)
  559. (:func:`make_option` is a factory function for creating Option instances;
  560. currently it is an alias for the Option constructor. A future version of
  561. :mod:`optparse` may split Option into several classes, and :func:`make_option`
  562. will pick the right class to instantiate. Do not instantiate Option directly.)
  563. .. _optparse-defining-options:
  564. Defining options
  565. ^^^^^^^^^^^^^^^^
  566. Each Option instance represents a set of synonymous command-line option strings,
  567. e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
  568. long option strings, but you must specify at least one overall option string.
  569. The canonical way to create an :class:`Option` instance is with the
  570. :meth:`add_option` method of :class:`OptionParser`.
  571. .. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
  572. To define an option with only a short option string::
  573. parser.add_option("-f", attr=value, ...)
  574. And to define an option with only a long option string::
  575. parser.add_option("--foo", attr=value, ...)
  576. The keyword arguments define attributes of the new Option object. The most
  577. important option attribute is :attr:`~Option.action`, and it largely
  578. determines which other attributes are relevant or required. If you pass
  579. irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
  580. raises an :exc:`OptionError` exception explaining your mistake.
  581. An option's *action* determines what :mod:`optparse` does when it encounters
  582. this option on the command-line. The standard option actions hard-coded into
  583. :mod:`optparse` are:
  584. ``"store"``
  585. store this option's argument (default)
  586. ``"store_const"``
  587. store a constant value
  588. ``"store_true"``
  589. store a true value
  590. ``"store_false"``
  591. store a false value
  592. ``"append"``
  593. append this option's argument to a list
  594. ``"append_const"``
  595. append a constant value to a list
  596. ``"count"``
  597. increment a counter by one
  598. ``"callback"``
  599. call a specified function
  600. ``"help"``
  601. print a usage message including all options and the documentation for them
  602. (If you don't supply an action, the default is ``"store"``. For this action,
  603. you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
  604. attributes; see :ref:`optparse-standard-option-actions`.)
  605. As you can see, most actions involve storing or updating a value somewhere.
  606. :mod:`optparse` always creates a special object for this, conventionally called
  607. ``options`` (it happens to be an instance of :class:`optparse.Values`). Option
  608. arguments (and various other values) are stored as attributes of this object,
  609. according to the :attr:`~Option.dest` (destination) option attribute.
  610. For example, when you call ::
  611. parser.parse_args()
  612. one of the first things :mod:`optparse` does is create the ``options`` object::
  613. options = Values()
  614. If one of the options in this parser is defined with ::
  615. parser.add_option("-f", "--file", action="store", type="string", dest="filename")
  616. and the command-line being parsed includes any of the following::
  617. -ffoo
  618. -f foo
  619. --file=foo
  620. --file foo
  621. then :mod:`optparse`, on seeing this option, will do the equivalent of ::
  622. options.filename = "foo"
  623. The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
  624. as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
  625. one that makes sense for *all* options.
  626. .. _optparse-option-attributes:
  627. Option attributes
  628. ^^^^^^^^^^^^^^^^^
  629. The following option attributes may be passed as keyword arguments to
  630. :meth:`OptionParser.add_option`. If you pass an option attribute that is not
  631. relevant to a particular option, or fail to pass a required option attribute,
  632. :mod:`optparse` raises :exc:`OptionError`.
  633. .. attribute:: Option.action
  634. (default: ``"store"``)
  635. Determines :mod:`optparse`'s behaviour when this option is seen on the
  636. command line; the available options are documented :ref:`here
  637. <optparse-standard-option-actions>`.
  638. .. attribute:: Option.type
  639. (default: ``"string"``)
  640. The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
  641. the available option types are documented :ref:`here
  642. <optparse-standard-option-types>`.
  643. .. attribute:: Option.dest
  644. (default: derived from option strings)
  645. If the option's action implies writing or modifying a value somewhere, this
  646. tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
  647. attribute of the ``options`` object that :mod:`optparse` builds as it parses
  648. the command line.
  649. .. attribute:: Option.default
  650. The value to use for this option's destination if the option is not seen on
  651. the command line. See also :meth:`OptionParser.set_defaults`.
  652. .. attribute:: Option.nargs
  653. (default: 1)
  654. How many arguments of type :attr:`~Option.type` should be consumed when this
  655. option is seen. If > 1, :mod:`optparse` will store a tuple of values to
  656. :attr:`~Option.dest`.
  657. .. attribute:: Option.const
  658. For actions that store a constant value, the constant value to store.
  659. .. attribute:: Option.choices
  660. For options of type ``"choice"``, the list of strings the user may choose
  661. from.
  662. .. attribute:: Option.callback
  663. For options with action ``"callback"``, the callable to call when this option
  664. is seen. See section :ref:`optparse-option-callbacks` for detail on the
  665. arguments passed to the callable.
  666. .. attribute:: Option.callback_args
  667. Option.callback_kwargs
  668. Additional positional and keyword arguments to pass to ``callback`` after the
  669. four standard callback arguments.
  670. .. attribute:: Option.help
  671. Help text to print for this option when listing all available options after
  672. the user supplies a :attr:`~Option.help` option (such as ``"--help"``). If
  673. no help text is supplied, the option will be listed without help text. To
  674. hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
  675. .. attribute:: Option.metavar
  676. (default: derived from option strings)
  677. Stand-in for the option argument(s) to use when printing help text. See
  678. section :ref:`optparse-tutorial` for an example.
  679. .. _optparse-standard-option-actions:
  680. Standard option actions
  681. ^^^^^^^^^^^^^^^^^^^^^^^
  682. The various option actions all have slightly different requirements and effects.
  683. Most actions have several relevant option attributes which you may specify to
  684. guide :mod:`optparse`'s behaviour; a few have required attributes, which you
  685. must specify for any option using that action.
  686. * ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
  687. :attr:`~Option.nargs`, :attr:`~Option.choices`]
  688. The option must be followed by an argument, which is converted to a value
  689. according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
  690. :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
  691. command line; all will be converted according to :attr:`~Option.type` and
  692. stored to :attr:`~Option.dest` as a tuple. See the
  693. :ref:`optparse-standard-option-types` section.
  694. If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
  695. defaults to ``"choice"``.
  696. If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
  697. If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
  698. from the first long option string (e.g., ``"--foo-bar"`` implies
  699. ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
  700. destination from the first short option string (e.g., ``"-f"`` implies ``f``).
  701. Example::
  702. parser.add_option("-f")
  703. parser.add_option("-p", type="float", nargs=3, dest="point")
  704. As it parses the command line ::
  705. -f foo.txt -p 1 -3.5 4 -fbar.txt
  706. :mod:`optparse` will set ::
  707. options.f = "foo.txt"
  708. options.point = (1.0, -3.5, 4.0)
  709. options.f = "bar.txt"
  710. * ``"store_const"`` [required: :attr:`~Option.const`; relevant:
  711. :attr:`~Option.dest`]
  712. The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
  713. Example::
  714. parser.add_option("-q", "--quiet",
  715. action="store_const", const=0, dest="verbose")
  716. parser.add_option("-v", "--verbose",
  717. action="store_const", const=1, dest="verbose")
  718. parser.add_option("--noisy",
  719. action="store_const", const=2, dest="verbose")
  720. If ``"--noisy"`` is seen, :mod:`optparse` will set ::
  721. options.verbose = 2
  722. * ``"store_true"`` [relevant: :attr:`~Option.dest`]
  723. A special case of ``"store_const"`` that stores a true value to
  724. :attr:`~Option.dest`.
  725. * ``"store_false"`` [relevant: :attr:`~Option.dest`]
  726. Like ``"store_true"``, but stores a false value.
  727. Example::
  728. parser.add_option("--clobber", action="store_true", dest="clobber")
  729. parser.add_option("--no-clobber", action="store_false", dest="clobber")
  730. * ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
  731. :attr:`~Option.nargs`, :attr:`~Option.choices`]
  732. The option must be followed by an argument, which is appended to the list in
  733. :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
  734. supplied, an empty list is automatically created when :mod:`optparse` first
  735. encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
  736. multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
  737. is appended to :attr:`~Option.dest`.
  738. The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
  739. for the ``"store"`` action.
  740. Example::
  741. parser.add_option("-t", "--tracks", action="append", type="int")
  742. If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
  743. of::
  744. options.tracks = []
  745. options.tracks.append(int("3"))
  746. If, a little later on, ``"--tracks=4"`` is seen, it does::
  747. options.tracks.append(int("4"))
  748. * ``"append_const"`` [required: :attr:`~Option.const`; relevant:
  749. :attr:`~Option.dest`]
  750. Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
  751. :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
  752. ``None``, and an empty list is automatically created the first time the option
  753. is encountered.
  754. * ``"count"`` [relevant: :attr:`~Option.dest`]
  755. Increment the integer stored at :attr:`~Option.dest`. If no default value is
  756. supplied, :attr:`~Option.dest` is set to zero before being incremented the
  757. first time.
  758. Example::
  759. parser.add_option("-v", action="count", dest="verbosity")
  760. The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
  761. equivalent of::
  762. options.verbosity = 0
  763. options.verbosity += 1
  764. Every subsequent occurrence of ``"-v"`` results in ::
  765. options.verbosity += 1
  766. * ``"callback"`` [required: :attr:`~Option.callback`; relevant:
  767. :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
  768. :attr:`~Option.callback_kwargs`]
  769. Call the function specified by :attr:`~Option.callback`, which is called as ::
  770. func(option, opt_str, value, parser, *args, **kwargs)
  771. See section :ref:`optparse-option-callbacks` for more detail.
  772. * ``"help"``
  773. Prints a complete help message for all the options in the current option
  774. parser. The help message is constructed from the ``usage`` string passed to
  775. OptionParser's constructor and the :attr:`~Option.help` string passed to every
  776. option.
  777. If no :attr:`~Option.help` string is supplied for an option, it will still be
  778. listed in the help message. To omit an option entirely, use the special value
  779. :data:`optparse.SUPPRESS_HELP`.
  780. :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
  781. OptionParsers, so you do not normally need to create one.
  782. Example::
  783. from optparse import OptionParser, SUPPRESS_HELP
  784. # usually, a help option is added automatically, but that can
  785. # be suppressed using the add_help_option argument
  786. parser = OptionParser(add_help_option=False)
  787. parser.add_option("-h", "--help", action="help")
  788. parser.add_option("-v", action="store_true", dest="verbose",
  789. help="Be moderately verbose")
  790. parser.add_option("--file", dest="filename",
  791. help="Input file to read data from")
  792. parser.add_option("--secret", help=SUPPRESS_HELP)
  793. If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
  794. it will print something like the following help message to stdout (assuming
  795. ``sys.argv[0]`` is ``"foo.py"``)::
  796. usage: foo.py [options]
  797. options:
  798. -h, --help Show this help message and exit
  799. -v Be moderately verbose
  800. --file=FILENAME Input file to read data from
  801. After printing the help message, :mod:`optparse` terminates your process with
  802. ``sys.exit(0)``.
  803. * ``"version"``
  804. Prints the version number supplied to the OptionParser to stdout and exits.
  805. The version number is actually formatted and printed by the
  806. ``print_version()`` method of OptionParser. Generally only relevant if the
  807. ``version`` argument is supplied to the OptionParser constructor. As with
  808. :attr:`~Option.help` options, you will rarely create ``version`` options,
  809. since :mod:`optparse` automatically adds them when needed.
  810. .. _optparse-standard-option-types:
  811. Standard option types
  812. ^^^^^^^^^^^^^^^^^^^^^
  813. :mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
  814. ``"long"``, ``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
  815. option types, see section :ref:`optparse-extending-optparse`.
  816. Arguments to string options are not checked or converted in any way: the text on
  817. the command line is stored in the destination (or passed to the callback) as-is.
  818. Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:
  819. * if the number starts with ``0x``, it is parsed as a hexadecimal number
  820. * if the number starts with ``0``, it is parsed as an octal number
  821. * if the number starts with ``0b``, it is parsed as a binary number
  822. * otherwise, the number is parsed as a decimal number
  823. The conversion is done by calling either :func:`int` or :func:`long` with the
  824. appropriate base (2, 8, 10, or 16). If this fails, so will :mod:`optparse`,
  825. although with a more useful error message.
  826. ``"float"`` and ``"complex"`` option arguments are converted directly with
  827. :func:`float` and :func:`complex`, with similar error-handling.
  828. ``"choice"`` options are a subtype of ``"string"`` options. The
  829. :attr:`~Option.choices`` option attribute (a sequence of strings) defines the
  830. set of allowed option arguments. :func:`optparse.check_choice` compares
  831. user-supplied option arguments against this master list and raises
  832. :exc:`OptionValueError` if an invalid string is given.
  833. .. _optparse-parsing-arguments:
  834. Parsing arguments
  835. ^^^^^^^^^^^^^^^^^
  836. The whole point of creating and populating an OptionParser is to call its
  837. :meth:`parse_args` method::
  838. (options, args) = parser.parse_args(args=None, values=None)
  839. where the input parameters are
  840. ``args``
  841. the list of arguments to process (default: ``sys.argv[1:]``)
  842. ``values``
  843. object to store option arguments in (default: a new instance of
  844. :class:`optparse.Values`)
  845. and the return values are
  846. ``options``
  847. the same object that was passed in as ``values``, or the optparse.Values
  848. instance created by :mod:`optparse`
  849. ``args``
  850. the leftover positional arguments after all options have been processed
  851. The most common usage is to supply neither keyword argument. If you supply
  852. ``values``, it will be modified with repeated :func:`setattr` calls (roughly one
  853. for every option argument stored to an option destination) and returned by
  854. :meth:`parse_args`.
  855. If :meth:`parse_args` encounters any errors in the argument list, it calls the
  856. OptionParser's :meth:`error` method with an appropriate end-user error message.
  857. This ultimately terminates your process with an exit status of 2 (the
  858. traditional Unix exit status for command-line errors).
  859. .. _optparse-querying-manipulating-option-parser:
  860. Querying and manipulating your option parser
  861. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  862. The default behavior of the option parser can be customized slightly, and you
  863. can also poke around your option parser and see what's there. OptionParser
  864. provides several methods to help you out:
  865. .. method:: OptionParser.disable_interspersed_args()
  866. Set parsing to stop on the first non-option. For example, if ``"-a"`` and
  867. ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
  868. normally accepts this syntax::
  869. prog -a arg1 -b arg2
  870. and treats it as equivalent to ::
  871. prog -a -b arg1 arg2
  872. To disable this feature, call :meth:`disable_interspersed_args`. This
  873. restores traditional Unix syntax, where option parsing stops with the first
  874. non-option argument.
  875. Use this if you have a command processor which runs another command which has
  876. options of its own and you want to make sure these options don't get
  877. confused. For example, each command might have a different set of options.
  878. .. method:: OptionParser.enable_interspersed_args()
  879. Set parsing to not stop on the first non-option, allowing interspersing
  880. switches with command arguments. This is the default behavior.
  881. .. method:: OptionParser.get_option(opt_str)
  882. Returns the Option instance with the option string *opt_str*, or ``None`` if
  883. no options have that option string.
  884. .. method:: OptionParser.has_option(opt_str)
  885. Return true if the OptionParser has an option with option string *opt_str*
  886. (e.g., ``"-q"`` or ``"--verbose"``).
  887. .. method:: OptionParser.remove_option(opt_str)
  888. If the :class:`OptionParser` has an option corresponding to *opt_str*, that
  889. option is removed. If that option provided any other option strings, all of
  890. those option strings become invalid. If *opt_str* does not occur in any
  891. option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
  892. .. _optparse-conflicts-between-options:
  893. Conflicts between options
  894. ^^^^^^^^^^^^^^^^^^^^^^^^^
  895. If you're not careful, it's easy to define options with conflicting option
  896. strings::
  897. parser.add_option("-n", "--dry-run", ...)
  898. [...]
  899. parser.add_option("-n", "--noisy", ...)
  900. (This is particularly true if you've defined your own OptionParser subclass with
  901. some standard options.)
  902. Every time you add an option, :mod:`optparse` checks for conflicts with existing
  903. options. If it finds any, it invokes the current conflict-handling mechanism.
  904. You can set the conflict-handling mechanism either in the constructor::
  905. parser = OptionParser(..., conflict_handler=handler)
  906. or with a separate call::
  907. parser.set_conflict_handler(handler)
  908. The available conflict handlers are:
  909. ``"error"`` (default)
  910. assume option conflicts are a programming error and raise
  911. :exc:`OptionConflictError`
  912. ``"resolve"``
  913. resolve option conflicts intelligently (see below)
  914. As an example, let's define an :class:`OptionParser` that resolves conflicts
  915. intelligently and add conflicting options to it::
  916. parser = OptionParser(conflict_handler="resolve")
  917. parser.add_option("-n", "--dry-run", ..., help="do no harm")
  918. parser.add_option("-n", "--noisy", ..., help="be noisy")
  919. At this point, :mod:`optparse` detects that a previously-added option is already
  920. using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
  921. it resolves the situation by removing ``"-n"`` from the earlier option's list of
  922. option strings. Now ``"--dry-run"`` is the only way for the user to activate
  923. that option. If the user asks for help, the help message will reflect that::
  924. options:
  925. --dry-run do no harm
  926. [...]
  927. -n, --noisy be noisy
  928. It's possible to whittle away the option strings for a previously-added option
  929. until there are none left, and the user has no way of invoking that option from
  930. the command-line. In that case, :mod:`optparse` removes that option completely,
  931. so it doesn't show up in help text or anywhere else. Carrying on with our
  932. existing OptionParser::
  933. parser.add_option("--dry-run", ..., help="new dry-run option")
  934. At this point, the original :option:`-n/--dry-run` option is no longer
  935. accessible, so :mod:`optparse` removes it, leaving this help text::
  936. options:
  937. [...]
  938. -n, --noisy be noisy
  939. --dry-run new dry-run option
  940. .. _optparse-cleanup:
  941. Cleanup
  942. ^^^^^^^
  943. OptionParser instances have several cyclic references. This should not be a
  944. problem for Python's garbage collector, but you may wish to break the cyclic
  945. references explicitly by calling :meth:`~OptionParser.destroy` on your
  946. OptionParser once you are done with it. This is particularly useful in
  947. long-running applications where large object graphs are reachable from your
  948. OptionParser.
  949. .. _optparse-other-methods:
  950. Other methods
  951. ^^^^^^^^^^^^^
  952. OptionParser supports several other public methods:
  953. .. method:: OptionParser.set_usage(usage)
  954. Set the usage string according to the rules described above for the ``usage``
  955. constructor keyword argument. Passing ``None`` sets the default usage
  956. string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
  957. .. method:: OptionParser.set_defaults(dest=value, ...)
  958. Set default values for several option destinations at once. Using
  959. :meth:`set_defaults` is the preferred way to set default values for options,
  960. since multiple options can share the same destination. For example, if
  961. several "mode" options all set the same destination, any one of them can set
  962. the default, and the last one wins::
  963. parser.add_option("--advanced", action="store_const",
  964. dest="mode", const="advanced",
  965. default="novice") # overridden below
  966. parser.add_option("--novice", action="store_const",
  967. dest="mode", const="novice",
  968. default="advanced") # overrides above setting
  969. To avoid this confusion, use :meth:`set_defaults`::
  970. parser.set_defaults(mode="advanced")
  971. parser.add_option("--advanced", action="store_const",
  972. dest="mode", const="advanced")
  973. parser.add_option("--novice", action="store_const",
  974. dest="mode", const="novice")
  975. .. _optparse-option-callbacks:
  976. Option Callbacks
  977. ----------------
  978. When :mod:`optparse`'s built-in actions and types aren't quite enough for your
  979. needs, you have two choices: extend :mod:`optparse` or define a callback option.
  980. Extending :mod:`optparse` is more general, but overkill for a lot of simple
  981. cases. Quite often a simple callback is all you need.
  982. There are two steps to defining a callback option:
  983. * define the option itself using the ``"callback"`` action
  984. * write the callback; this is a function (or method) that takes at least four
  985. arguments, as described below
  986. .. _optparse-defining-callback-option:
  987. Defining a callback option
  988. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  989. As always, the easiest way to define a callback option is by using the
  990. :meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
  991. only option attribute you must specify is ``callback``, the function to call::
  992. parser.add_option("-c", action="callback", callback=my_callback)
  993. ``callback`` is a function (or other callable object), so you must have already
  994. defined ``my_callback()`` when you create this callback option. In this simple
  995. case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
  996. which usually means that the option takes no arguments---the mere presence of
  997. :option:`-c` on the command-line is all it needs to know. In some
  998. circumstances, though, you might want your callback to consume an arbitrary
  999. number of command-line arguments. This is where writing callbacks gets tricky;
  1000. it's covered later in this section.
  1001. :mod:`optparse` always passes four particular arguments to your callback, and it
  1002. will only pass additional arguments if you specify them via
  1003. :attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
  1004. minimal callback function signature is::
  1005. def my_callback(option, opt, value, parser):
  1006. The four arguments to a callback are described below.
  1007. There are several other option attributes that you can supply when you define a
  1008. callback option:
  1009. :attr:`~Option.type`
  1010. has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
  1011. instructs :mod:`optparse` to consume one argument and convert it to
  1012. :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
  1013. though, :mod:`optparse` passes it to your callback function.
  1014. :attr:`~Option.nargs`
  1015. also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
  1016. consume :attr:`~Option.nargs` arguments, each of which must be convertible to
  1017. :attr:`~Option.type`. It then passes a tuple of converted values to your
  1018. callback.
  1019. :attr:`~Option.callback_args`
  1020. a tuple of extra positional arguments to pass to the callback
  1021. :attr:`~Option.callback_kwargs`
  1022. a dictionary of extra keyword arguments to pass to the callback
  1023. .. _optparse-how-callbacks-called:
  1024. How callbacks are called
  1025. ^^^^^^^^^^^^^^^^^^^^^^^^
  1026. All callbacks are called as follows::
  1027. func(option, opt_str, value, parser, *args, **kwargs)
  1028. where
  1029. ``option``
  1030. is the Option instance that's calling the callback
  1031. ``opt_str``
  1032. is the option string seen on the command-line that's triggering the callback.
  1033. (If an abbreviated long option was used, ``opt_str`` will be the full,
  1034. canonical option string---e.g. if the user puts ``"--foo"`` on the
  1035. command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
  1036. ``"--foobar"``.)
  1037. ``value``
  1038. is the argument to this option seen on the command-line. :mod:`optparse` will
  1039. only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
  1040. the type implied by the option's type. If :attr:`~Option.type` for this option is
  1041. ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
  1042. > 1, ``value`` will be a tuple of values of the appropriate type.
  1043. ``parser``
  1044. is the OptionParser instance driving the whole thing, mainly useful because
  1045. you can access some other interesting data through its instance attributes:
  1046. ``parser.largs``
  1047. the current list of leftover arguments, ie. arguments that have been
  1048. consumed but are neither options nor option arguments. Feel free to modify
  1049. ``parser.largs``, e.g. by adding more arguments to it. (This list will
  1050. become ``args``, the second return value of :meth:`parse_args`.)
  1051. ``parser.rargs``
  1052. the current list of remaining arguments, ie. with ``opt_str`` and
  1053. ``value`` (if applicable) removed, and only the arguments following them
  1054. still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
  1055. arguments.
  1056. ``parser.values``
  1057. the object where option values are by default stored (an instance of
  1058. optparse.OptionValues). This lets callbacks use the same mechanism as the
  1059. rest of :mod:`optparse` for storing option values; you don't need to mess
  1060. around with globals or closures. You can also access or modify the
  1061. value(s) of any options already encountered on the command-line.
  1062. ``args``
  1063. is a tuple of arbitrary positional arguments supplied via the
  1064. :attr:`~Option.callback_args` option attribute.
  1065. ``kwargs``
  1066. is a dictionary of arbitrary keyword arguments supplied via
  1067. :attr:`~Option.callback_kwargs`.
  1068. .. _optparse-raising-errors-in-callback:
  1069. Raising errors in a callback
  1070. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1071. The callback function should raise :exc:`OptionValueError` if there are any
  1072. problems with the option or its argument(s). :mod:`optparse` catches this and
  1073. terminates the program, printing the error message you supply to stderr. Your
  1074. message should be clear, concise, accurate, and mention the option at fault.
  1075. Otherwise, the user will have a hard time figuring out what he did wrong.
  1076. .. _optparse-callback-example-1:
  1077. Callback example 1: trivial callback
  1078. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1079. Here's an example of a callback option that takes no arguments, and simply
  1080. records that the option was seen::
  1081. def record_foo_seen(option, opt_str, value, parser):
  1082. parser.values.saw_foo = True
  1083. parser.add_option("--foo", action="callback", callback=record_foo_seen)
  1084. Of course, you could do that with the ``"store_true"`` action.
  1085. .. _optparse-callback-example-2:
  1086. Callback example 2: check option order
  1087. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1088. Here's a slightly more interesting example: record the fact that ``"-a"`` is
  1089. seen, but blow up if it comes after ``"-b"`` in the command-line. ::
  1090. def check_order(option, opt_str, value, parser):
  1091. if parser.values.b:
  1092. raise OptionValueError("can't use -a after -b")
  1093. parser.values.a = 1
  1094. [...]
  1095. parser.add_option("-a", action="callback", callback=check_order)
  1096. parser.add_option("-b", action="store_true", dest="b")
  1097. .. _optparse-callback-example-3:
  1098. Callback example 3: check option order (generalized)
  1099. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1100. If you want to re-use this callback for several similar options (set a flag, but
  1101. blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
  1102. message and the flag that it sets must be generalized. ::
  1103. def check_order(option, opt_str, value, parser):
  1104. if parser.values.b:
  1105. raise OptionValueError("can't use %s after -b" % opt_str)
  1106. setattr(parser.values, option.dest, 1)
  1107. [...]
  1108. parser.add_option("-a", action="callback", callback=check_order, dest='a')
  1109. parser.add_option("-b", action="store_true", dest="b")
  1110. parser.add_option("-c", action="callback", callback=check_order, dest='c')
  1111. .. _optparse-callback-example-4:
  1112. Callback example 4: check arbitrary condition
  1113. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1114. Of course, you could put any condition in there---you're not limited to checking
  1115. the values of already-defined options. For example, if you have options that
  1116. should not be called when the moon is full, all you have to do is this::
  1117. def check_moon(option, opt_str, value, parser):
  1118. if is_moon_full():
  1119. raise OptionValueError("%s option invalid when moon is full"
  1120. % opt_str)
  1121. setattr(parser.values, option.dest, 1)
  1122. [...]
  1123. parser.add_option("--foo",
  1124. action="callback", callback=check_moon, dest="foo")
  1125. (The definition of ``is_moon_full()`` is left as an exercise for the reader.)
  1126. .. _optparse-callback-example-5:
  1127. Callback example 5: fixed arguments
  1128. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1129. Things get slightly more interesting when you define callback options that take
  1130. a fixed number of arguments. Specifying that a callback option takes arguments
  1131. is similar to defining a ``"store"`` or ``"append"`` option: if you define
  1132. :attr:`~Option.type`, then the option takes one argument that must be
  1133. convertible to that type; if you further define :attr:`~Option.nargs`, then the
  1134. option takes :attr:`~Option.nargs` arguments.
  1135. Here's an example that just emulates the standard ``"store"`` action::
  1136. def store_value(option, opt_str, value, parser):
  1137. setattr(parser.values, option.dest, value)
  1138. [...]
  1139. parser.add_option("--foo",
  1140. action="callback", callback=store_value,
  1141. type="int", nargs=3, dest="foo")
  1142. Note that :mod:`optparse` takes care of consuming 3 arguments and converting
  1143. them to integers for you; all you have to do is store them. (Or whatever;
  1144. obviously you don't need a callback for this example.)
  1145. .. _optparse-callback-example-6:
  1146. Callback example 6: variable arguments
  1147. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1148. Things get hairy when you want an option to take a variable number of arguments.
  1149. For this case, you must write a callback, as :mod:`optparse` doesn't provide any
  1150. built-in capabilities for it. And you have to deal with certain intricacies of
  1151. conventional Unix command-line parsing that :mod:`optparse` normally handles for
  1152. you. In particular, callbacks should implement the conventional rules for bare
  1153. ``"--"`` and ``"-"`` arguments:
  1154. * either ``"--"`` or ``"-"`` can be option arguments
  1155. * bare ``"--"`` (if not the argument to some option): halt command-line
  1156. processing and discard the ``"--"``
  1157. * bare ``"-"`` (if not the argument to some option): halt command-line
  1158. processing but keep the ``"-"`` (append it to ``parser.largs``)
  1159. If you want an option that takes a variable number of arguments, there are
  1160. several subtle, tricky issues to worry about. The exact implementation you
  1161. choose will be based on which trade-offs you're willing to make for your
  1162. application (which is why :mod:`optparse` doesn't support this sort of thing
  1163. directly).
  1164. Nevertheless, here's a stab at a callback for an option with variable
  1165. arguments::
  1166. def vararg_callback(option, opt_str, value, parser):
  1167. assert value is None
  1168. value = []
  1169. def floatable(str):
  1170. try:
  1171. float(str)
  1172. return True
  1173. except ValueError:
  1174. return False
  1175. for arg in parser.rargs:
  1176. # stop on --foo like options
  1177. if arg[:2] == "--" and len(arg) > 2:
  1178. break
  1179. # stop on -a, but not on -3 or -3.0
  1180. if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
  1181. break
  1182. value.append(arg)
  1183. del parser.rargs[:len(value)]
  1184. setattr(parser.values, option.dest, value)
  1185. [...]
  1186. parser.add_option("-c", "--callback", dest="vararg_attr",
  1187. action="callback", callback=vararg_callback)
  1188. .. _optparse-extending-optparse:
  1189. Extending :mod:`optparse`
  1190. -------------------------
  1191. Since the two major controlling factors in how :mod:`optparse` interprets
  1192. command-line options are the action and type of each option, the most likely
  1193. direction of extension is to add new actions and new types.
  1194. .. _optparse-adding-new-types:
  1195. Adding new types
  1196. ^^^^^^^^^^^^^^^^
  1197. To add new types, you need to define your own subclass of :mod:`optparse`'s
  1198. :class:`Option` class. This class has a couple of attributes that define
  1199. :mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
  1200. .. attribute:: Option.TYPES
  1201. A tuple of type names; in your subclass, simply define a new tuple
  1202. :attr:`TYPES` that builds on the standard one.
  1203. .. attribute:: Option.TYPE_CHECKER
  1204. A dictionary mapping type names to type-checking functions. A type-checking
  1205. function has the following signature::
  1206. def check_mytype(option, opt, value)
  1207. where ``option`` is an :class:`Option` instance, ``opt`` is an option string
  1208. (e.g., ``"-f"``), and ``value`` is the string from the command line that must
  1209. be checked and converted to your desired type. ``check_mytype()`` should
  1210. return an object of the hypothetical type ``mytype``. The value returned by
  1211. a type-checking function will wind up in the OptionValues instance returned
  1212. by :meth:`OptionParser.parse_args`, or be passed to a callback as the
  1213. ``value`` parameter.
  1214. Your type-checking function should raise :exc:`OptionValueError` if it
  1215. encounters any problems. :exc:`OptionValueError` takes a single string
  1216. argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
  1217. method, which in turn prepends the program name and the string ``"error:"``
  1218. and prints everything to stderr before terminating the process.
  1219. Here's a silly example that demonstrates adding a ``"complex"`` option type to
  1220. parse Python-style complex numbers on the command line. (This is even sillier
  1221. than it used to be, because :mod:`optparse` 1.3 added built-in support for
  1222. complex numbers, but never mind.)
  1223. First, the necessary imports::
  1224. from copy import copy
  1225. from optparse import Option, OptionValueError
  1226. You need to define your type-checker first, since it's referred to later (in the
  1227. :attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
  1228. def check_complex(option, opt, value):
  1229. try:
  1230. return complex(value)
  1231. except ValueError:
  1232. raise OptionValueError(
  1233. "option %s: invalid complex value: %r" % (opt, value))
  1234. Finally, the Option subclass::
  1235. class MyOption (Option):
  1236. TYPES = Option.TYPES + ("complex",)
  1237. TYPE_CHECKER = copy(Option.TYPE_CHECKER)
  1238. TYPE_CHECKER["complex"] = check_complex
  1239. (If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
  1240. up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
  1241. Option class. This being Python, nothing stops you from doing that except good
  1242. manners and common sense.)
  1243. That's it! Now you can write a script that uses the new option type just like
  1244. any other :mod:`optparse`\ -based script, except you have to instruct your
  1245. OptionParser to use MyOption instead of Option::
  1246. parser = OptionParser(option_class=MyOption)
  1247. parser.add_option("-c", type="complex")
  1248. Alternately, you can build your own option list and pass it to OptionParser; if
  1249. you don't use :meth:`add_option` in the above way, you don't need to tell
  1250. OptionParser which option class to use::
  1251. option_list = [MyOption("-c", action="store", type="complex", dest="c")]
  1252. parser = OptionParser(option_list=option_list)
  1253. .. _optparse-adding-new-actions:
  1254. Adding new actions
  1255. ^^^^^^^^^^^^^^^^^^
  1256. Adding new actions is a bit trickier, because you have to understand that
  1257. :mod:`optparse` has a couple of classifications for actions:
  1258. "store" actions
  1259. actions that result in :mod:`optparse` storing a value to an attribute of the
  1260. current OptionValues instance; these options require a :attr:`~Option.dest`
  1261. attribute to be supplied to the Option constructor.
  1262. "typed" actions
  1263. actions that take a value from the command line and expect it to be of a
  1264. certain type; or rather, a string that can be converted to a certain type.
  1265. These options require a :attr:`~Option.type` attribute to the Option
  1266. constructor.
  1267. These are overlapping sets: some default "store" actions are ``"store"``,
  1268. ``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
  1269. actions are ``"store"``, ``"append"``, and ``"callback"``.
  1270. When you add an action, you need to categorize it by listing it in at least one
  1271. of the following class attributes of Option (all are lists of strings):
  1272. .. attribute:: Option.ACTIONS
  1273. All actions must be listed in ACTIONS.
  1274. .. attribute:: Option.STORE_ACTIONS
  1275. "store" actions are additionally listed here.
  1276. .. attribute:: Option.TYPED_ACTIONS
  1277. "typed" actions are additionally listed here.
  1278. .. attribute:: Option.ALWAYS_TYPED_ACTIONS
  1279. Actions that always take a type (i.e. whose options always take a value) are
  1280. additionally listed here. The only effect of this is that :mod:`optparse`
  1281. assigns the default type, ``"string"``, to options with no explicit type
  1282. whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
  1283. In order to actually implement your new action, you must override Option's
  1284. :meth:`take_action` method and add a case that recognizes your action.
  1285. For example, let's add an ``"extend"`` action. This is similar to the standard
  1286. ``"append"`` action, but instead of taking a single value from the command-line
  1287. and appending it to an existing list, ``"extend"`` will take multiple values in
  1288. a single comma-delimited string, and extend an existing list with them. That
  1289. is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
  1290. line ::
  1291. --names=foo,bar --names blah --names ding,dong
  1292. would result in a list ::
  1293. ["foo", "bar", "blah", "ding", "dong"]
  1294. Again we define a subclass of Option::
  1295. class MyOption (Option):
  1296. ACTIONS = Option.ACTIONS + ("extend",)
  1297. STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
  1298. TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
  1299. ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
  1300. def take_action(self, action, dest, opt, value, values, parser):
  1301. if action == "extend":
  1302. lvalue = value.split(",")
  1303. values.ensure_value(dest, []).extend(lvalue)
  1304. else:
  1305. Option.take_action(
  1306. self, action, dest, opt, value, values, parser)
  1307. Features of note:
  1308. * ``"extend"`` both expects a value on the command-line and stores that value
  1309. somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
  1310. :attr:`~Option.TYPED_ACTIONS`.
  1311. * to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
  1312. ``"extend"`` actions, we put the ``"extend"`` action in
  1313. :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
  1314. * :meth:`MyOption.take_action` implements just this one new action, and passes
  1315. control back to :meth:`Option.take_action` for the standard :mod:`optparse`
  1316. actions.
  1317. * ``values`` is an instance of the optparse_parser.Values class, which provides
  1318. the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
  1319. essentially :func:`getattr` with a safety valve; it is called as ::
  1320. values.ensure_value(attr, value)
  1321. If the ``attr`` attribute of ``values`` doesn't exist or is None, then
  1322. ensure_value() first sets it to ``value``, and then returns 'value. This is
  1323. very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
  1324. of which accumulate data in a variable and expect that variable to be of a
  1325. certain type (a list for the first two, an integer for the latter). Using
  1326. :meth:`ensure_value` means that scripts using your action don't have to worry
  1327. about setting a default value for the option destinations in question; they
  1328. can just leave the default as None and :meth:`ensure_value` will take care of
  1329. getting it right when it's needed.