source: python/trunk/Doc/library/getopt.rst

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

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