blob: 7f6b6703ae899f1153474a3d57072849a81a046a [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`getopt` --- Parser for command line options
2=================================================
3
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
8
9This module helps scripts to parse the command line arguments in ``sys.argv``.
10It supports the same conventions as the Unix :cfunc:`getopt` function (including
Christian Heimes5b5e81c2007-12-31 16:14:33 +000011the special meanings of arguments of the form '``-``' and '``--``'). Long
Georg Brandl116aa622007-08-15 14:28:22 +000012options similar to those supported by GNU software may be used as well via an
Benjamin Petersonae5360b2008-09-08 23:05:23 +000013optional third argument.
14
15A more convenient, flexible, and powerful alternative is the
16:mod:`optparse` module.
17
18This module provides two functions and an
Georg Brandl116aa622007-08-15 14:28:22 +000019exception:
20
Georg Brandl116aa622007-08-15 14:28:22 +000021
Georg Brandl036490d2009-05-17 13:00:36 +000022.. function:: getopt(args, shortopts, longopts=[])
Georg Brandl116aa622007-08-15 14:28:22 +000023
24 Parses command line options and parameter list. *args* is the argument list to
25 be parsed, without the leading reference to the running program. Typically, this
Georg Brandl036490d2009-05-17 13:00:36 +000026 means ``sys.argv[1:]``. *shortopts* is the string of option letters that the
Georg Brandl116aa622007-08-15 14:28:22 +000027 script wants to recognize, with options that require an argument followed by a
28 colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses).
29
30 .. note::
31
Georg Brandl036490d2009-05-17 13:00:36 +000032 Unlike GNU :cfunc:`getopt`, after a non-option argument, all further
33 arguments are considered also non-options. This is similar to the way
34 non-GNU Unix systems work.
Georg Brandl116aa622007-08-15 14:28:22 +000035
Georg Brandl036490d2009-05-17 13:00:36 +000036 *longopts*, if specified, must be a list of strings with the names of the
Georg Brandl81ac1ce2007-08-31 17:17:17 +000037 long options which should be supported. The leading ``'--'`` characters
Georg Brandl116aa622007-08-15 14:28:22 +000038 should not be included in the option name. Long options which require an
39 argument should be followed by an equal sign (``'='``). To accept only long
Georg Brandl036490d2009-05-17 13:00:36 +000040 options, *shortopts* should be an empty string. Long options on the command line
Georg Brandl116aa622007-08-15 14:28:22 +000041 can be recognized so long as they provide a prefix of the option name that
Georg Brandl036490d2009-05-17 13:00:36 +000042 matches exactly one of the accepted options. For example, if *longopts* is
Georg Brandl116aa622007-08-15 14:28:22 +000043 ``['foo', 'frob']``, the option :option:`--fo` will match as :option:`--foo`,
44 but :option:`--f` will not match uniquely, so :exc:`GetoptError` will be raised.
45
46 The return value consists of two elements: the first is a list of ``(option,
47 value)`` pairs; the second is the list of program arguments left after the
48 option list was stripped (this is a trailing slice of *args*). Each
49 option-and-value pair returned has the option as its first element, prefixed
50 with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
Georg Brandl81ac1ce2007-08-31 17:17:17 +000051 options (e.g., ``'--long-option'``), and the option argument as its
Georg Brandl116aa622007-08-15 14:28:22 +000052 second 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, thus
54 allowing multiple occurrences. Long and short options may be mixed.
55
56
Georg Brandl036490d2009-05-17 13:00:36 +000057.. function:: gnu_getopt(args, shortopts, longopts=[])
Georg Brandl116aa622007-08-15 14:28:22 +000058
59 This function works like :func:`getopt`, except that GNU style scanning mode is
60 used by default. This means that option and non-option arguments may be
61 intermixed. The :func:`getopt` function stops processing options as soon as a
62 non-option argument is encountered.
63
64 If the first character of the option string is '+', or if the environment
Georg Brandlaf265f42008-12-07 15:06:20 +000065 variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
66 soon as a non-option argument is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +000067
Georg Brandl116aa622007-08-15 14:28:22 +000068
69.. exception:: GetoptError
70
71 This is raised when an unrecognized option is found in the argument list or when
72 an option requiring an argument is given none. The argument to the exception is
73 a string indicating the cause of the error. For long options, an argument given
74 to an option which does not require one will also cause this exception to be
75 raised. The attributes :attr:`msg` and :attr:`opt` give the error message and
76 related option; if there is no specific option to which the exception relates,
77 :attr:`opt` is an empty string.
78
Georg Brandl55ac8f02007-09-01 13:51:09 +000079.. XXX deprecated?
Georg Brandl116aa622007-08-15 14:28:22 +000080.. exception:: error
81
82 Alias for :exc:`GetoptError`; for backward compatibility.
83
Christian Heimesfe337bf2008-03-23 21:54:12 +000084An example using only Unix style options:
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 >>> import getopt
87 >>> args = '-a -b -cfoo -d bar a1 a2'.split()
88 >>> args
89 ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
90 >>> optlist, args = getopt.getopt(args, 'abc:d:')
91 >>> optlist
92 [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
93 >>> args
94 ['a1', 'a2']
95
Christian Heimesfe337bf2008-03-23 21:54:12 +000096Using long option names is equally easy:
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
99 >>> args = s.split()
100 >>> args
101 ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
102 >>> optlist, args = getopt.getopt(args, 'x', [
103 ... 'condition=', 'output-file=', 'testing'])
104 >>> optlist
Christian Heimesfe337bf2008-03-23 21:54:12 +0000105 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
Georg Brandl116aa622007-08-15 14:28:22 +0000106 >>> args
107 ['a1', 'a2']
108
109In a script, typical usage is something like this::
110
111 import getopt, sys
112
113 def main():
114 try:
115 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
116 except getopt.GetoptError as err:
117 # print help information and exit:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000118 print(err) # will print something like "option -a not recognized"
Georg Brandl116aa622007-08-15 14:28:22 +0000119 usage()
120 sys.exit(2)
121 output = None
122 verbose = False
123 for o, a in opts:
124 if o == "-v":
125 verbose = True
126 elif o in ("-h", "--help"):
127 usage()
128 sys.exit()
129 elif o in ("-o", "--output"):
130 output = a
131 else:
132 assert False, "unhandled option"
133 # ...
134
135 if __name__ == "__main__":
136 main()
137
138
139.. seealso::
140
141 Module :mod:`optparse`
142 More object-oriented command line option parsing.
143