PageRenderTime 14ms CodeModel.GetById 9ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

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