blob: bcfc4b59c4783204f2c60b29a33251a3938e8c5c [file] [log] [blame]
Steven Bethard6d265692010-03-02 09:22:57 +00001:mod:`getopt` --- C-style parser for command line options
2=========================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: getopt
Georg Brandl036490d2009-05-17 13:00:36 +00005 :synopsis: Portable parser for command line options; support both short and
6 long option names.
Georg Brandl116aa622007-08-15 14:28:22 +00007
Raymond Hettinger469271d2011-01-27 20:38:46 +00008**Source code:** :source:`Lib/getopt.py`
9
10--------------
11
Steven Bethard59710962010-05-24 03:21:08 +000012.. note::
13 The :mod:`getopt` module is a parser for command line options whose API is
Georg Brandl60203b42010-10-06 10:11:56 +000014 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
Steven Bethard59710962010-05-24 03:21:08 +000016 less code and get better help and error messages should consider using the
17 :mod:`argparse` module instead.
Georg Brandl116aa622007-08-15 14:28:22 +000018
19This module helps scripts to parse the command line arguments in ``sys.argv``.
Georg Brandl60203b42010-10-06 10:11:56 +000020It supports the same conventions as the Unix :c:func:`getopt` function (including
Christian Heimes5b5e81c2007-12-31 16:14:33 +000021the special meanings of arguments of the form '``-``' and '``--``'). Long
Georg Brandl116aa622007-08-15 14:28:22 +000022options similar to those supported by GNU software may be used as well via an
Benjamin Petersonae5360b2008-09-08 23:05:23 +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 Brandl116aa622007-08-15 14:28:22 +000029exception:
30
Georg Brandl116aa622007-08-15 14:28:22 +000031
Georg Brandl036490d2009-05-17 13:00:36 +000032.. function:: getopt(args, shortopts, longopts=[])
Georg Brandl116aa622007-08-15 14:28:22 +000033
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
Georg Brandl036490d2009-05-17 13:00:36 +000036 means ``sys.argv[1:]``. *shortopts* is the string of option letters that the
Georg Brandl116aa622007-08-15 14:28:22 +000037 script wants to recognize, with options that require an argument followed by a
Georg Brandl60203b42010-10-06 10:11:56 +000038 colon (``':'``; i.e., the same format that Unix :c:func:`getopt` uses).
Georg Brandl116aa622007-08-15 14:28:22 +000039
40 .. note::
41
Georg Brandl60203b42010-10-06 10:11:56 +000042 Unlike GNU :c:func:`getopt`, after a non-option argument, all further
Georg Brandl036490d2009-05-17 13:00:36 +000043 arguments are considered also non-options. This is similar to the way
44 non-GNU Unix systems work.
Georg Brandl116aa622007-08-15 14:28:22 +000045
Georg Brandl036490d2009-05-17 13:00:36 +000046 *longopts*, if specified, must be a list of strings with the names of the
Georg Brandl81ac1ce2007-08-31 17:17:17 +000047 long options which should be supported. The leading ``'--'`` characters
Georg Brandl116aa622007-08-15 14:28:22 +000048 should not be included in the option name. Long options which require an
Georg Brandl495f7b52009-10-27 15:28:25 +000049 argument should be followed by an equal sign (``'='``). Optional arguments
50 are not supported. To accept only long options, *shortopts* should be an
51 empty string. Long options on the command line can be recognized so long as
52 they provide a prefix of the option name that matches exactly one of the
53 accepted options. For example, if *longopts* is ``['foo', 'frob']``, the
Éric Araujo713d3032010-11-18 16:38:46 +000054 option ``--fo`` will match as ``--foo``, but ``--f`` will
Georg Brandl495f7b52009-10-27 15:28:25 +000055 not match uniquely, so :exc:`GetoptError` will be raised.
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl81ac1ce2007-08-31 17:17:17 +000062 options (e.g., ``'--long-option'``), and the option argument as its
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl036490d2009-05-17 13:00:36 +000068.. function:: gnu_getopt(args, shortopts, longopts=[])
Georg Brandl116aa622007-08-15 14:28:22 +000069
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 Araujo713d3032010-11-18 16:38:46 +000075 If the first character of the option string is ``'+'``, or if the environment
Georg Brandlaf265f42008-12-07 15:06:20 +000076 variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
77 soon as a non-option argument is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +000078
Georg Brandl116aa622007-08-15 14:28:22 +000079
80.. exception:: GetoptError
81
82 This is raised when an unrecognized option is found in the argument list or when
83 an option requiring an argument is given none. The argument to the exception is
84 a string indicating the cause of the error. For long options, an argument given
85 to an option which does not require one will also cause this exception to be
86 raised. The attributes :attr:`msg` and :attr:`opt` give the error message and
87 related option; if there is no specific option to which the exception relates,
88 :attr:`opt` is an empty string.
89
Georg Brandl55ac8f02007-09-01 13:51:09 +000090.. XXX deprecated?
Georg Brandl116aa622007-08-15 14:28:22 +000091.. exception:: error
92
93 Alias for :exc:`GetoptError`; for backward compatibility.
94
Christian Heimesfe337bf2008-03-23 21:54:12 +000095An example using only Unix style options:
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 >>> import getopt
98 >>> args = '-a -b -cfoo -d bar a1 a2'.split()
99 >>> args
100 ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
101 >>> optlist, args = getopt.getopt(args, 'abc:d:')
102 >>> optlist
103 [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
104 >>> args
105 ['a1', 'a2']
106
Christian Heimesfe337bf2008-03-23 21:54:12 +0000107Using long option names is equally easy:
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109 >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
110 >>> args = s.split()
111 >>> args
112 ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
113 >>> optlist, args = getopt.getopt(args, 'x', [
114 ... 'condition=', 'output-file=', 'testing'])
115 >>> optlist
Christian Heimesfe337bf2008-03-23 21:54:12 +0000116 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
Georg Brandl116aa622007-08-15 14:28:22 +0000117 >>> args
118 ['a1', 'a2']
119
120In a script, typical usage is something like this::
121
122 import getopt, sys
123
124 def main():
125 try:
126 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
127 except getopt.GetoptError as err:
128 # print help information and exit:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000129 print(err) # will print something like "option -a not recognized"
Georg Brandl116aa622007-08-15 14:28:22 +0000130 usage()
131 sys.exit(2)
132 output = None
133 verbose = False
134 for o, a in opts:
135 if o == "-v":
136 verbose = True
137 elif o in ("-h", "--help"):
138 usage()
139 sys.exit()
140 elif o in ("-o", "--output"):
141 output = a
142 else:
143 assert False, "unhandled option"
144 # ...
145
146 if __name__ == "__main__":
147 main()
148
Steven Bethard59710962010-05-24 03:21:08 +0000149Note that an equivalent command line interface could be produced with less code
150and more informative help and error messages by using the :mod:`argparse` module::
151
152 import argparse
153
154 if __name__ == '__main__':
155 parser = argparse.ArgumentParser()
156 parser.add_argument('-o', '--output')
157 parser.add_argument('-v', dest='verbose', action='store_true')
158 args = parser.parse_args()
159 # ... do something with args.output ...
160 # ... do something with args.verbose ..
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162.. seealso::
163
Steven Bethard59710962010-05-24 03:21:08 +0000164 Module :mod:`argparse`
165 Alternative command line option and argument parsing library.
Georg Brandl116aa622007-08-15 14:28:22 +0000166