blob: fb6820fdc88bdb03a02b6103393a03e581fdf376 [file] [log] [blame]
Steven Betharde9330e72010-03-02 08:38:09 +00001:mod:`getopt` --- C-style parser for command line options
2=========================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00003
4.. module:: getopt
5 :synopsis: Portable parser for command line options; support both short and long option
6 names.
7
Éric Araujo29a0b572011-08-19 02:14:03 +02008**Source code:** :source:`Lib/getopt.py`
9
10--------------
11
Steven Bethard74bd9cf2010-05-24 02:38:00 +000012.. 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 :cfunc:`getopt` function. Users who
15 are unfamiliar with the C :cfunc:`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.
Georg Brandl8ec7f652007-08-15 14:28:01 +000018
19This module helps scripts to parse the command line arguments in ``sys.argv``.
20It supports the same conventions as the Unix :cfunc:`getopt` function (including
Georg Brandlb19be572007-12-29 10:57:00 +000021the special meanings of arguments of the form '``-``' and '``--``'). Long
Georg Brandl8ec7f652007-08-15 14:28:01 +000022options similar to those supported by GNU software may be used as well via an
Mark Summerfieldffde3cf2008-09-08 14:45:37 +000023optional third argument.
24
25A more convenient, flexible, and powerful alternative is the
26:mod:`optparse` module.
27
28This module provides two functions and an
Georg Brandl8ec7f652007-08-15 14:28:01 +000029exception:
30
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
32.. function:: getopt(args, options[, long_options])
33
34 Parses command line options and parameter list. *args* is the argument list to
35 be parsed, without the leading reference to the running program. Typically, this
36 means ``sys.argv[1:]``. *options* is the string of option letters that the
37 script wants to recognize, with options that require an argument followed by a
38 colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses).
39
40 .. note::
41
Georg Brandld1bed8e2009-10-22 15:54:35 +000042 Unlike GNU :cfunc:`getopt`, after a non-option argument, all further
43 arguments are considered also non-options. This is similar to the way
44 non-GNU Unix systems work.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
46 *long_options*, if specified, must be a list of strings with the names of the
Éric Araujoa8132ec2010-12-16 03:53:53 +000047 long options which should be supported. The leading ``'--'``
Georg Brandld1bed8e2009-10-22 15:54:35 +000048 characters should not be included in the option name. Long options which
49 require an argument should be followed by an equal sign (``'='``). Optional
50 arguments are not supported. To accept only long options, *options* should
51 be an empty string. Long options on the command line can be recognized so
52 long as they provide a prefix of the option name that matches exactly one of
53 the accepted options. For example, if *long_options* is ``['foo', 'frob']``,
Éric Araujoa8132ec2010-12-16 03:53:53 +000054 the option ``--fo`` will match as ``--foo``, but ``--f``
Georg Brandld1bed8e2009-10-22 15:54:35 +000055 will not match uniquely, so :exc:`GetoptError` will be raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +000056
57 The return value consists of two elements: the first is a list of ``(option,
58 value)`` pairs; the second is the list of program arguments left after the
59 option list was stripped (this is a trailing slice of *args*). Each
60 option-and-value pair returned has the option as its first element, prefixed
61 with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
Éric Araujoa8132ec2010-12-16 03:53:53 +000062 options (e.g., ``'--long-option'``), and the option argument as its
Georg Brandl8ec7f652007-08-15 14:28:01 +000063 second element, or an empty string if the option has no argument. The
64 options occur in the list in the same order in which they were found, thus
65 allowing multiple occurrences. Long and short options may be mixed.
66
67
68.. function:: gnu_getopt(args, options[, long_options])
69
70 This function works like :func:`getopt`, except that GNU style scanning mode is
71 used by default. This means that option and non-option arguments may be
72 intermixed. The :func:`getopt` function stops processing options as soon as a
73 non-option argument is encountered.
74
Éric Araujoa8132ec2010-12-16 03:53:53 +000075 If the first character of the option string is ``'+'``, or if the environment
Georg Brandl8d6c4902008-12-05 09:13:45 +000076 variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
77 soon as a non-option argument is encountered.
Georg Brandl8ec7f652007-08-15 14:28:01 +000078
79 .. versionadded:: 2.3
80
81
82.. exception:: GetoptError
83
84 This is raised when an unrecognized option is found in the argument list or when
85 an option requiring an argument is given none. The argument to the exception is
86 a string indicating the cause of the error. For long options, an argument given
87 to an option which does not require one will also cause this exception to be
88 raised. The attributes :attr:`msg` and :attr:`opt` give the error message and
89 related option; if there is no specific option to which the exception relates,
90 :attr:`opt` is an empty string.
91
92 .. versionchanged:: 1.6
93 Introduced :exc:`GetoptError` as a synonym for :exc:`error`.
94
95
96.. exception:: error
97
98 Alias for :exc:`GetoptError`; for backward compatibility.
99
Georg Brandle8f1b002008-03-22 22:04:10 +0000100An example using only Unix style options:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101
102 >>> import getopt
103 >>> args = '-a -b -cfoo -d bar a1 a2'.split()
104 >>> args
105 ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
106 >>> optlist, args = getopt.getopt(args, 'abc:d:')
107 >>> optlist
108 [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
109 >>> args
110 ['a1', 'a2']
111
Georg Brandle8f1b002008-03-22 22:04:10 +0000112Using long option names is equally easy:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113
114 >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
115 >>> args = s.split()
116 >>> args
117 ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
118 >>> optlist, args = getopt.getopt(args, 'x', [
119 ... 'condition=', 'output-file=', 'testing'])
120 >>> optlist
Georg Brandle8f1b002008-03-22 22:04:10 +0000121 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000122 >>> args
123 ['a1', 'a2']
124
125In a script, typical usage is something like this::
126
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000127 import getopt, sys
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128
129 def main():
130 try:
131 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
132 except getopt.GetoptError, err:
133 # print help information and exit:
134 print str(err) # will print something like "option -a not recognized"
135 usage()
136 sys.exit(2)
137 output = None
138 verbose = False
139 for o, a in opts:
140 if o == "-v":
141 verbose = True
142 elif o in ("-h", "--help"):
143 usage()
144 sys.exit()
145 elif o in ("-o", "--output"):
146 output = a
147 else:
148 assert False, "unhandled option"
149 # ...
150
151 if __name__ == "__main__":
152 main()
153
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000154Note that an equivalent command line interface could be produced with less code
155and more informative help and error messages by using the :mod:`argparse` module::
156
157 import argparse
158
159 if __name__ == '__main__':
160 parser = argparse.ArgumentParser()
161 parser.add_argument('-o', '--output')
162 parser.add_argument('-v', dest='verbose', action='store_true')
163 args = parser.parse_args()
164 # ... do something with args.output ...
165 # ... do something with args.verbose ..
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166
167.. seealso::
168
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000169 Module :mod:`argparse`
170 Alternative command line option and argument parsing library.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171