blob: 250d31f4756496b95d7f853fc2c33adc195422bf [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Standard Module \sectcode{getopt}}
2
3\stmodindex{getopt}
4This module helps scripts to parse the command line arguments in
5\code{sys.argv}.
6It uses the same conventions as the \UNIX{}
7\code{getopt()}
8function.
9It defines the function
10\code{getopt.getopt(args, options)}
11and the exception
12\code{getopt.error}.
13
14The first argument to
15\code{getopt()}
16is the argument list passed to the script with its first element
17chopped off (i.e.,
18\code{sys.argv[1:]}).
19The second argument is the string of option letters that the
20script wants to recognize, with options that require an argument
21followed by a colon (i.e., the same format that \UNIX{}
22\code{getopt()}
23uses).
24The return value consists of two elements: the first is a list of
25option-and-value pairs; the second is the list of program arguments
26left after the option list was stripped (this is a trailing slice of the
27first argument).
28Each option-and-value pair returned has the option as its first element,
29prefixed with a hyphen (e.g.,
30\code{'-x'}),
31and the option argument as its second element, or an empty string if the
32option has no argument.
33The options occur in the list in the same order in which they were
34found, thus allowing multiple occurrences.
35Example:
36
37\bcode\begin{verbatim}
38>>> import getopt, string
39>>> args = string.split('-a -b -cfoo -d bar a1 a2')
40>>> args
41['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
42>>> optlist, args = getopt.getopt(args, 'abc:d:')
43>>> optlist
44[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
45>>> args
46['a1', 'a2']
47>>>
48\end{verbatim}\ecode
49
50The exception
51\code{getopt.error = 'getopt error'}
52is raised when an unrecognized option is found in the argument list or
53when an option requiring an argument is given none.
54The argument to the exception is a string indicating the cause of the
55error.