/Doc/library/getopt.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 149 lines · 112 code · 37 blank · 0 comment · 0 complexity · 4c144ea551680218b9893419162af8c0 MD5 · raw file

  1. :mod:`getopt` --- Parser for command line options
  2. =================================================
  3. .. module:: getopt
  4. :synopsis: Portable parser for command line options; support both short and long option
  5. names.
  6. This module helps scripts to parse the command line arguments in ``sys.argv``.
  7. It supports the same conventions as the Unix :cfunc:`getopt` function (including
  8. the special meanings of arguments of the form '``-``' and '``--``'). Long
  9. options similar to those supported by GNU software may be used as well via an
  10. optional third argument.
  11. A more convenient, flexible, and powerful alternative is the
  12. :mod:`optparse` module.
  13. This module provides two functions and an
  14. exception:
  15. .. function:: getopt(args, options[, long_options])
  16. Parses command line options and parameter list. *args* is the argument list to
  17. be parsed, without the leading reference to the running program. Typically, this
  18. means ``sys.argv[1:]``. *options* is the string of option letters that the
  19. script wants to recognize, with options that require an argument followed by a
  20. colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses).
  21. .. note::
  22. Unlike GNU :cfunc:`getopt`, after a non-option argument, all further arguments
  23. are considered also non-options. This is similar to the way non-GNU Unix systems
  24. work.
  25. *long_options*, if specified, must be a list of strings with the names of the
  26. long options which should be supported. The leading ``'-``\ ``-'`` characters
  27. should not be included in the option name. Long options which require an
  28. argument should be followed by an equal sign (``'='``). To accept only long
  29. options, *options* should be an empty string. Long options on the command line
  30. can be recognized so long as they provide a prefix of the option name that
  31. matches exactly one of the accepted options. For example, if *long_options* is
  32. ``['foo', 'frob']``, the option :option:`--fo` will match as :option:`--foo`,
  33. but :option:`--f` will not match uniquely, so :exc:`GetoptError` will be raised.
  34. The return value consists of two elements: the first is a list of ``(option,
  35. value)`` pairs; the second is the list of program arguments left after the
  36. option list was stripped (this is a trailing slice of *args*). Each
  37. option-and-value pair returned has the option as its first element, prefixed
  38. with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
  39. options (e.g., ``'-``\ ``-long-option'``), and the option argument as its
  40. second element, or an empty string if the option has no argument. The
  41. options occur in the list in the same order in which they were found, thus
  42. allowing multiple occurrences. Long and short options may be mixed.
  43. .. function:: gnu_getopt(args, options[, long_options])
  44. This function works like :func:`getopt`, except that GNU style scanning mode is
  45. used by default. This means that option and non-option arguments may be
  46. intermixed. The :func:`getopt` function stops processing options as soon as a
  47. non-option argument is encountered.
  48. If the first character of the option string is '+', or if the environment
  49. variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
  50. soon as a non-option argument is encountered.
  51. .. versionadded:: 2.3
  52. .. exception:: GetoptError
  53. This is raised when an unrecognized option is found in the argument list or when
  54. an option requiring an argument is given none. The argument to the exception is
  55. a string indicating the cause of the error. For long options, an argument given
  56. to an option which does not require one will also cause this exception to be
  57. raised. The attributes :attr:`msg` and :attr:`opt` give the error message and
  58. related option; if there is no specific option to which the exception relates,
  59. :attr:`opt` is an empty string.
  60. .. versionchanged:: 1.6
  61. Introduced :exc:`GetoptError` as a synonym for :exc:`error`.
  62. .. exception:: error
  63. Alias for :exc:`GetoptError`; for backward compatibility.
  64. An example using only Unix style options:
  65. >>> import getopt
  66. >>> args = '-a -b -cfoo -d bar a1 a2'.split()
  67. >>> args
  68. ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
  69. >>> optlist, args = getopt.getopt(args, 'abc:d:')
  70. >>> optlist
  71. [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
  72. >>> args
  73. ['a1', 'a2']
  74. Using long option names is equally easy:
  75. >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
  76. >>> args = s.split()
  77. >>> args
  78. ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
  79. >>> optlist, args = getopt.getopt(args, 'x', [
  80. ... 'condition=', 'output-file=', 'testing'])
  81. >>> optlist
  82. [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
  83. >>> args
  84. ['a1', 'a2']
  85. In a script, typical usage is something like this::
  86. import getopt, sys
  87. def main():
  88. try:
  89. opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
  90. except getopt.GetoptError, err:
  91. # print help information and exit:
  92. print str(err) # will print something like "option -a not recognized"
  93. usage()
  94. sys.exit(2)
  95. output = None
  96. verbose = False
  97. for o, a in opts:
  98. if o == "-v":
  99. verbose = True
  100. elif o in ("-h", "--help"):
  101. usage()
  102. sys.exit()
  103. elif o in ("-o", "--output"):
  104. output = a
  105. else:
  106. assert False, "unhandled option"
  107. # ...
  108. if __name__ == "__main__":
  109. main()
  110. .. seealso::
  111. Module :mod:`optparse`
  112. More object-oriented command line option parsing.