blob: 94ba90e3a929a8cb6e88de0c192ad55dfb0d930c [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Christian Heimes5b5e81c2007-12-31 16:14:33 +000012the special meanings of arguments of the form '``-``' and '``--``'). Long
Georg Brandl116aa622007-08-15 14:28:22 +000013options similar to those supported by GNU software may be used as well via an
Benjamin Petersonae5360b2008-09-08 23:05:23 +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 Brandl116aa622007-08-15 14:28:22 +000020exception:
21
Georg Brandl116aa622007-08-15 14:28:22 +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
33 Unlike GNU :cfunc:`getopt`, after a non-option argument, all further arguments
34 are considered also non-options. This is similar to the way non-GNU Unix systems
35 work.
36
37 *long_options*, if specified, must be a list of strings with the names of the
Georg Brandl81ac1ce2007-08-31 17:17:17 +000038 long options which should be supported. The leading ``'--'`` characters
Georg Brandl116aa622007-08-15 14:28:22 +000039 should not be included in the option name. Long options which require an
40 argument should be followed by an equal sign (``'='``). To accept only long
41 options, *options* should be an empty string. Long options on the command line
42 can be recognized so long as they provide a prefix of the option name that
43 matches exactly one of the accepted options. For example, if *long_options* is
44 ``['foo', 'frob']``, the option :option:`--fo` will match as :option:`--foo`,
45 but :option:`--f` will not match uniquely, so :exc:`GetoptError` will be raised.
46
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
58.. function:: gnu_getopt(args, options[, long_options])
59
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