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