This commit was manufactured by cvs2svn to create tag 'r241c1'.
[python/dscho.git] / Doc / lib / libgetopt.tex
blob3d582ebecbe237c909ca7486b87d4334c7fac316
1 \section{\module{getopt} ---
2 Parser for command line options}
4 \declaremodule{standard}{getopt}
5 \modulesynopsis{Portable parser for command line options; support both
6 short and long option names.}
9 This module helps scripts to parse the command line arguments in
10 \code{sys.argv}.
11 It supports the same conventions as the \UNIX{} \cfunction{getopt()}
12 function (including the special meanings of arguments of the form
13 `\code{-}' and `\code{-}\code{-}').
14 % That's to fool latex2html into leaving the two hyphens alone!
15 Long options similar to those supported by
16 GNU software may be used as well via an optional third argument.
17 This module provides a single function and an exception:
19 \begin{funcdesc}{getopt}{args, options\optional{, long_options}}
20 Parses command line options and parameter list. \var{args} is the
21 argument list to be parsed, without the leading reference to the
22 running program. Typically, this means \samp{sys.argv[1:]}.
23 \var{options} is the string of option letters that the script wants to
24 recognize, with options that require an argument followed by a colon
25 (\character{:}; i.e., the same format that \UNIX{}
26 \cfunction{getopt()} uses).
28 \note{Unlike GNU \cfunction{getopt()}, after a non-option
29 argument, all further arguments are considered also non-options.
30 This is similar to the way non-GNU \UNIX{} systems work.}
32 \var{long_options}, if specified, must be a list of strings with the
33 names of the long options which should be supported. The leading
34 \code{'-}\code{-'} characters should not be included in the option
35 name. Long options which require an argument should be followed by an
36 equal sign (\character{=}). To accept only long options,
37 \var{options} should be an empty string. Long options on the command
38 line can be recognized so long as they provide a prefix of the option
39 name that matches exactly one of the accepted options. For example,
40 if \var{long_options} is \code{['foo', 'frob']}, the option
41 \longprogramopt{fo} will match as \longprogramopt{foo}, but
42 \longprogramopt{f} will not match uniquely, so \exception{GetoptError}
43 will be raised.
45 The return value consists of two elements: the first is a list of
46 \code{(\var{option}, \var{value})} pairs; the second is the list of
47 program arguments left after the option list was stripped (this is a
48 trailing slice of \var{args}). Each option-and-value pair returned
49 has the option as its first element, prefixed with a hyphen for short
50 options (e.g., \code{'-x'}) or two hyphens for long options (e.g.,
51 \code{'-}\code{-long-option'}), and the option argument as its second
52 element, or an empty string if the option has no argument. The
53 options occur in the list in the same order in which they were found,
54 thus allowing multiple occurrences. Long and short options may be
55 mixed.
56 \end{funcdesc}
58 \begin{funcdesc}{gnu_getopt}{args, options\optional{, long_options}}
59 This function works like \function{getopt()}, except that GNU style
60 scanning mode is used by default. This means that option and
61 non-option arguments may be intermixed. The \function{getopt()}
62 function stops processing options as soon as a non-option argument is
63 encountered.
65 If the first character of the option string is `+', or if the
66 environment variable POSIXLY_CORRECT is set, then option processing
67 stops as soon as a non-option argument is encountered.
68 \end{funcdesc}
70 \begin{excdesc}{GetoptError}
71 This is raised when an unrecognized option is found in the argument
72 list or when an option requiring an argument is given none.
73 The argument to the exception is a string indicating the cause of the
74 error. For long options, an argument given to an option which does
75 not require one will also cause this exception to be raised. The
76 attributes \member{msg} and \member{opt} give the error message and
77 related option; if there is no specific option to which the exception
78 relates, \member{opt} is an empty string.
80 \versionchanged[Introduced \exception{GetoptError} as a synonym for
81 \exception{error}]{1.6}
82 \end{excdesc}
84 \begin{excdesc}{error}
85 Alias for \exception{GetoptError}; for backward compatibility.
86 \end{excdesc}
89 An example using only \UNIX{} style options:
91 \begin{verbatim}
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 \end{verbatim}
103 Using long option names is equally easy:
105 \begin{verbatim}
106 >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
107 >>> args = s.split()
108 >>> args
109 ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
110 >>> optlist, args = getopt.getopt(args, 'x', [
111 ... 'condition=', 'output-file=', 'testing'])
112 >>> optlist
113 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x',
114 '')]
115 >>> args
116 ['a1', 'a2']
117 \end{verbatim}
119 In a script, typical usage is something like this:
121 \begin{verbatim}
122 import getopt, sys
124 def main():
125 try:
126 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
127 except getopt.GetoptError:
128 # print help information and exit:
129 usage()
130 sys.exit(2)
131 output = None
132 verbose = False
133 for o, a in opts:
134 if o == "-v":
135 verbose = True
136 if o in ("-h", "--help"):
137 usage()
138 sys.exit()
139 if o in ("-o", "--output"):
140 output = a
141 # ...
143 if __name__ == "__main__":
144 main()
145 \end{verbatim}
147 \begin{seealso}
148 \seemodule{optparse}{More object-oriented command line option parsing.}
149 \end{seealso}