blob: 11fec5b14144b1aefcddafb9f7807fc61de24ee8 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`getopt` --- Parser for command line options
3=================================================
4
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
12the special meanings of arguments of the form '``-``' and '``-``\ ``-``'). Long
13options similar to those supported by GNU software may be used as well via an
14optional third argument. This module provides a single function and an
15exception:
16
17.. % That's to fool latex2html into leaving the two hyphens alone!
18
19
20.. function:: getopt(args, options[, long_options])
21
22 Parses command line options and parameter list. *args* is the argument list to
23 be parsed, without the leading reference to the running program. Typically, this
24 means ``sys.argv[1:]``. *options* is the string of option letters that the
25 script wants to recognize, with options that require an argument followed by a
26 colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses).
27
28 .. note::
29
30 Unlike GNU :cfunc:`getopt`, after a non-option argument, all further arguments
31 are considered also non-options. This is similar to the way non-GNU Unix systems
32 work.
33
34 *long_options*, if specified, must be a list of strings with the names of the
35 long options which should be supported. The leading ``'-``\ ``-'`` characters
36 should not be included in the option name. Long options which require an
37 argument should be followed by an equal sign (``'='``). To accept only long
38 options, *options* should be an empty string. Long options on the command line
39 can be recognized so long as they provide a prefix of the option name that
40 matches exactly one of the accepted options. For example, if *long_options* is
41 ``['foo', 'frob']``, the option :option:`--fo` will match as :option:`--foo`,
42 but :option:`--f` will not match uniquely, so :exc:`GetoptError` will be raised.
43
44 The return value consists of two elements: the first is a list of ``(option,
45 value)`` pairs; the second is the list of program arguments left after the
46 option list was stripped (this is a trailing slice of *args*). Each
47 option-and-value pair returned has the option as its first element, prefixed
48 with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
49 options (e.g., ``'-``\ ``-long-option'``), and the option argument as its
50 second element, or an empty string if the option has no argument. The
51 options occur in the list in the same order in which they were found, thus
52 allowing multiple occurrences. Long and short options may be mixed.
53
54
55.. function:: gnu_getopt(args, options[, long_options])
56
57 This function works like :func:`getopt`, except that GNU style scanning mode is
58 used by default. This means that option and non-option arguments may be
59 intermixed. The :func:`getopt` function stops processing options as soon as a
60 non-option argument is encountered.
61
62 If the first character of the option string is '+', or if the environment
63 variable POSIXLY_CORRECT is set, then option processing stops as soon as a
64 non-option argument is encountered.
65
66 .. versionadded:: 2.3
67
68
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
79 .. versionchanged:: 1.6
80 Introduced :exc:`GetoptError` as a synonym for :exc:`error`.
81
82
83.. exception:: error
84
85 Alias for :exc:`GetoptError`; for backward compatibility.
86
87An example using only Unix style options::
88
89 >>> import getopt
90 >>> args = '-a -b -cfoo -d bar a1 a2'.split()
91 >>> args
92 ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
93 >>> optlist, args = getopt.getopt(args, 'abc:d:')
94 >>> optlist
95 [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
96 >>> args
97 ['a1', 'a2']
98
99Using long option names is equally easy::
100
101 >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
102 >>> args = s.split()
103 >>> args
104 ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
105 >>> optlist, args = getopt.getopt(args, 'x', [
106 ... 'condition=', 'output-file=', 'testing'])
107 >>> optlist
108 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x',
109 '')]
110 >>> args
111 ['a1', 'a2']
112
113In a script, typical usage is something like this::
114
115 import getopt, sys
116
117 def main():
118 try:
119 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
120 except getopt.GetoptError, err:
121 # print help information and exit:
122 print str(err) # will print something like "option -a not recognized"
123 usage()
124 sys.exit(2)
125 output = None
126 verbose = False
127 for o, a in opts:
128 if o == "-v":
129 verbose = True
130 elif o in ("-h", "--help"):
131 usage()
132 sys.exit()
133 elif o in ("-o", "--output"):
134 output = a
135 else:
136 assert False, "unhandled option"
137 # ...
138
139 if __name__ == "__main__":
140 main()
141
142
143.. seealso::
144
145 Module :mod:`optparse`
146 More object-oriented command line option parsing.
147