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