blob: 91bf34342e20511ec6dfd59d54713af609bcb906 [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
9
10This module helps scripts to parse the command line arguments in ``sys.argv``.
11It supports the same conventions as the Unix :cfunc:`getopt` function (including
Georg Brandlb19be572007-12-29 10:57:00 +000012the special meanings of arguments of the form '``-``' and '``--``'). Long
Georg Brandl8ec7f652007-08-15 14:28:01 +000013options similar to those supported by GNU software may be used as well via an
Mark Summerfieldffde3cf2008-09-08 14:45:37 +000014optional third argument.
15
16A more convenient, flexible, and powerful alternative is the
17:mod:`optparse` module.
18
19This module provides two functions and an
Georg Brandl8ec7f652007-08-15 14:28:01 +000020exception:
21
Georg Brandl8ec7f652007-08-15 14:28:01 +000022
23.. function:: getopt(args, options[, long_options])
24
25 Parses command line options and parameter list. *args* is the argument list to
26 be parsed, without the leading reference to the running program. Typically, this
27 means ``sys.argv[1:]``. *options* is the string of option letters that the
28 script wants to recognize, with options that require an argument followed by a
29 colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses).
30
31 .. note::
32
Georg Brandld1bed8e2009-10-22 15:54:35 +000033 Unlike GNU :cfunc:`getopt`, after a non-option argument, all further
34 arguments are considered also non-options. This is similar to the way
35 non-GNU Unix systems work.
Georg Brandl8ec7f652007-08-15 14:28:01 +000036
37 *long_options*, if specified, must be a list of strings with the names of the
Georg Brandld1bed8e2009-10-22 15:54:35 +000038 long options which should be supported. The leading ``'-``\ ``-'``
39 characters should not be included in the option name. Long options which
40 require an argument should be followed by an equal sign (``'='``). Optional
41 arguments are not supported. To accept only long options, *options* should
42 be an empty string. Long options on the command line can be recognized so
43 long as they provide a prefix of the option name that matches exactly one of
44 the accepted options. For example, if *long_options* is ``['foo', 'frob']``,
45 the option :option:`--fo` will match as :option:`--foo`, but :option:`--f`
46 will not match uniquely, so :exc:`GetoptError` will be raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +000047
48 The return value consists of two elements: the first is a list of ``(option,
49 value)`` pairs; the second is the list of program arguments left after the
50 option list was stripped (this is a trailing slice of *args*). Each
51 option-and-value pair returned has the option as its first element, prefixed
52 with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
53 options (e.g., ``'-``\ ``-long-option'``), and the option argument as its
54 second element, or an empty string if the option has no argument. The
55 options occur in the list in the same order in which they were found, thus
56 allowing multiple occurrences. Long and short options may be mixed.
57
58
59.. function:: gnu_getopt(args, options[, long_options])
60
61 This function works like :func:`getopt`, except that GNU style scanning mode is
62 used by default. This means that option and non-option arguments may be
63 intermixed. The :func:`getopt` function stops processing options as soon as a
64 non-option argument is encountered.
65
66 If the first character of the option string is '+', or if the environment
Georg Brandl8d6c4902008-12-05 09:13:45 +000067 variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
68 soon as a non-option argument is encountered.
Georg Brandl8ec7f652007-08-15 14:28:01 +000069
70 .. versionadded:: 2.3
71
72
73.. exception:: GetoptError
74
75 This is raised when an unrecognized option is found in the argument list or when
76 an option requiring an argument is given none. The argument to the exception is
77 a string indicating the cause of the error. For long options, an argument given
78 to an option which does not require one will also cause this exception to be
79 raised. The attributes :attr:`msg` and :attr:`opt` give the error message and
80 related option; if there is no specific option to which the exception relates,
81 :attr:`opt` is an empty string.
82
83 .. versionchanged:: 1.6
84 Introduced :exc:`GetoptError` as a synonym for :exc:`error`.
85
86
87.. exception:: error
88
89 Alias for :exc:`GetoptError`; for backward compatibility.
90
Georg Brandle8f1b002008-03-22 22:04:10 +000091An example using only Unix style options:
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
93 >>> import getopt
94 >>> args = '-a -b -cfoo -d bar a1 a2'.split()
95 >>> args
96 ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
97 >>> optlist, args = getopt.getopt(args, 'abc:d:')
98 >>> optlist
99 [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
100 >>> args
101 ['a1', 'a2']
102
Georg Brandle8f1b002008-03-22 22:04:10 +0000103Using long option names is equally easy:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104
105 >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
106 >>> args = s.split()
107 >>> args
108 ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
109 >>> optlist, args = getopt.getopt(args, 'x', [
110 ... 'condition=', 'output-file=', 'testing'])
111 >>> optlist
Georg Brandle8f1b002008-03-22 22:04:10 +0000112 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113 >>> args
114 ['a1', 'a2']
115
116In a script, typical usage is something like this::
117
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000118 import getopt, sys
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119
120 def main():
121 try:
122 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
123 except getopt.GetoptError, err:
124 # print help information and exit:
125 print str(err) # will print something like "option -a not recognized"
126 usage()
127 sys.exit(2)
128 output = None
129 verbose = False
130 for o, a in opts:
131 if o == "-v":
132 verbose = True
133 elif o in ("-h", "--help"):
134 usage()
135 sys.exit()
136 elif o in ("-o", "--output"):
137 output = a
138 else:
139 assert False, "unhandled option"
140 # ...
141
142 if __name__ == "__main__":
143 main()
144
145
146.. seealso::
147
148 Module :mod:`optparse`
149 More object-oriented command line option parsing.
150