/Doc/library/optparse.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 1901 lines · 1329 code · 572 blank · 0 comment · 0 complexity · a6c36a60dbbd380640ea5143f1d14569 MD5 · raw file

Large files are truncated click here to view the full file

  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 previ…