blob: a3603840b803e4f4ba6cd328d75761544de03913 [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
Georg Brandl495f7b52009-10-27 15:28:25 +000039 argument should be followed by an equal sign (``'='``). Optional arguments
40 are not supported. To accept only long options, *shortopts* should be an
41 empty string. Long options on the command line can be recognized so long as
42 they provide a prefix of the option name that matches exactly one of the
43 accepted options. For example, if *longopts* is ``['foo', 'frob']``, the
44 option :option:`--fo` will match as :option:`--foo`, but :option:`--f` will
45 not match uniquely, so :exc:`GetoptError` will be raised.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47 The return value consists of two elements: the first is a list of ``(option,
48 value)`` pairs; the second is the list of program arguments left after the
49 option list was stripped (this is a trailing slice of *args*). Each
50 option-and-value pair returned has the option as its first element, prefixed
51 with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
Georg Brandl81ac1ce2007-08-31 17:17:17 +000052 options (e.g., ``'--long-option'``), and the option argument as its
Georg Brandl116aa622007-08-15 14:28:22 +000053 second element, or an empty string if the option has no argument. The
54 options occur in the list in the same order in which they were found, thus
55 allowing multiple occurrences. Long and short options may be mixed.
56
57
Georg Brandl036490d2009-05-17 13:00:36 +000058.. function:: gnu_getopt(args, shortopts, longopts=[])
Georg Brandl116aa622007-08-15 14:28:22 +000059
60 This function works like :func:`getopt`, except that GNU style scanning mode is
61 used by default. This means that option and non-option arguments may be
62 intermixed. The :func:`getopt` function stops processing options as soon as a
63 non-option argument is encountered.
64
65 If the first character of the option string is '+', or if the environment
Georg Brandlaf265f42008-12-07 15:06:20 +000066 variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
67 soon as a non-option argument is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +000068
Georg Brandl116aa622007-08-15 14:28:22 +000069
70.. exception:: GetoptError
71
72 This is raised when an unrecognized option is found in the argument list or when
73 an option requiring an argument is given none. The argument to the exception is
74 a string indicating the cause of the error. For long options, an argument given
75 to an option which does not require one will also cause this exception to be
76 raised. The attributes :attr:`msg` and :attr:`opt` give the error message and
77 related option; if there is no specific option to which the exception relates,
78 :attr:`opt` is an empty string.
79
Georg Brandl55ac8f02007-09-01 13:51:09 +000080.. XXX deprecated?
Georg Brandl116aa622007-08-15 14:28:22 +000081.. exception:: error
82
83 Alias for :exc:`GetoptError`; for backward compatibility.
84
Christian Heimesfe337bf2008-03-23 21:54:12 +000085An example using only Unix style options:
Georg Brandl116aa622007-08-15 14:28:22 +000086
87 >>> import getopt
88 >>> args = '-a -b -cfoo -d bar a1 a2'.split()
89 >>> args
90 ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
91 >>> optlist, args = getopt.getopt(args, 'abc:d:')
92 >>> optlist
93 [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
94 >>> args
95 ['a1', 'a2']
96
Christian Heimesfe337bf2008-03-23 21:54:12 +000097Using long option names is equally easy:
Georg Brandl116aa622007-08-15 14:28:22 +000098
99 >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
100 >>> args = s.split()
101 >>> args
102 ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
103 >>> optlist, args = getopt.getopt(args, 'x', [
104 ... 'condition=', 'output-file=', 'testing'])
105 >>> optlist
Christian Heimesfe337bf2008-03-23 21:54:12 +0000106 [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
Georg Brandl116aa622007-08-15 14:28:22 +0000107 >>> args
108 ['a1', 'a2']
109
110In a script, typical usage is something like this::
111
112 import getopt, sys
113
114 def main():
115 try:
116 opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
117 except getopt.GetoptError as err:
118 # print help information and exit:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000119 print(err) # will print something like "option -a not recognized"
Georg Brandl116aa622007-08-15 14:28:22 +0000120 usage()
121 sys.exit(2)
122 output = None
123 verbose = False
124 for o, a in opts:
125 if o == "-v":
126 verbose = True
127 elif o in ("-h", "--help"):
128 usage()
129 sys.exit()
130 elif o in ("-o", "--output"):
131 output = a
132 else:
133 assert False, "unhandled option"
134 # ...
135
136 if __name__ == "__main__":
137 main()
138
139
140.. seealso::
141
142 Module :mod:`optparse`
143 More object-oriented command line option parsing.
144