blob: 4d65c79f96a4a2777f88633979749bcbd898da17 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
Steven Betharde9330e72010-03-02 08:38:09 +00002:mod:`getopt` --- C-style parser for command line options
3=========================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00004
5.. module:: getopt
6 :synopsis: Portable parser for command line options; support both short and long option
7 names.
8
Steven Bethard74bd9cf2010-05-24 02:38:00 +00009.. note::
10 The :mod:`getopt` module is a parser for command line options whose API is
11 designed to be familiar to users of the C :cfunc:`getopt` function. Users who
12 are unfamiliar with the C :cfunc:`getopt` function or who would like to write
13 less code and get better help and error messages should consider using the
14 :mod:`argparse` module instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +000015
16This module helps scripts to parse the command line arguments in ``sys.argv``.
17It supports the same conventions as the Unix :cfunc:`getopt` function (including
Georg Brandlb19be572007-12-29 10:57:00 +000018the special meanings of arguments of the form '``-``' and '``--``'). Long
Georg Brandl8ec7f652007-08-15 14:28:01 +000019options similar to those supported by GNU software may be used as well via an
Mark Summerfieldffde3cf2008-09-08 14:45:37 +000020optional third argument.
21
22A more convenient, flexible, and powerful alternative is the
23:mod:`optparse` module.
24
25This module provides two functions and an
Georg Brandl8ec7f652007-08-15 14:28:01 +000026exception:
27
Georg Brandl8ec7f652007-08-15 14:28:01 +000028
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
35 colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses).
36
37 .. note::
38
Georg Brandld1bed8e2009-10-22 15:54:35 +000039 Unlike GNU :cfunc:`getopt`, after a non-option argument, all further
40 arguments are considered also non-options. This is similar to the way
41 non-GNU Unix systems work.
Georg Brandl8ec7f652007-08-15 14:28:01 +000042
43 *long_options*, if specified, must be a list of strings with the names of the
Éric Araujoa8132ec2010-12-16 03:53:53 +000044 long options which should be supported. The leading ``'--'``
Georg Brandld1bed8e2009-10-22 15:54:35 +000045 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']``,
Éric Araujoa8132ec2010-12-16 03:53:53 +000051 the option ``--fo`` will match as ``--foo``, but ``--f``
Georg Brandld1bed8e2009-10-22 15:54:35 +000052 will not match uniquely, so :exc:`GetoptError` will be raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
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
Éric Araujoa8132ec2010-12-16 03:53:53 +000059 options (e.g., ``'--long-option'``), and the option argument as its
Georg Brandl8ec7f652007-08-15 14:28:01 +000060 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
Éric Araujoa8132ec2010-12-16 03:53:53 +000072 If the first character of the option string is ``'+'``, or if the environment
Georg Brandl8d6c4902008-12-05 09:13:45 +000073 variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
74 soon as a non-option argument is encountered.
Georg Brandl8ec7f652007-08-15 14:28:01 +000075
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
Georg Brandle8f1b002008-03-22 22:04:10 +000097An example using only Unix style options:
Georg Brandl8ec7f652007-08-15 14:28:01 +000098
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
Georg Brandle8f1b002008-03-22 22:04:10 +0000109Using long option names is equally easy:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000110
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
Georg Brandle8f1b002008-03-22 22:04:10 +0000118 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119 >>> args
120 ['a1', 'a2']
121
122In a script, typical usage is something like this::
123
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000124 import getopt, sys
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125
126 def main():
127 try:
128 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
129 except getopt.GetoptError, err:
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
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000151Note 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::
153
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 ..
Georg Brandl8ec7f652007-08-15 14:28:01 +0000163
164.. seealso::
165
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000166 Module :mod:`argparse`
167 Alternative command line option and argument parsing library.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168