Debian Codegraph @

Doc/library/getopt.rst

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