Guido van Rossum | 5fdeeea | 1994-01-02 01:22:07 +0000 | [diff] [blame] | 1 | \section{Standard Module \sectcode{getopt}} |
| 2 | |
| 3 | \stmodindex{getopt} |
| 4 | This module helps scripts to parse the command line arguments in |
| 5 | \code{sys.argv}. |
| 6 | It uses the same conventions as the \UNIX{} |
| 7 | \code{getopt()} |
Guido van Rossum | 470be14 | 1995-03-17 16:07:09 +0000 | [diff] [blame] | 8 | function (including the special meanings of arguments of the form |
| 9 | \samp{-} and \samp{--}). |
Guido van Rossum | 5fdeeea | 1994-01-02 01:22:07 +0000 | [diff] [blame] | 10 | It defines the function |
| 11 | \code{getopt.getopt(args, options)} |
| 12 | and the exception |
| 13 | \code{getopt.error}. |
| 14 | |
| 15 | The first argument to |
| 16 | \code{getopt()} |
| 17 | is the argument list passed to the script with its first element |
| 18 | chopped off (i.e., |
| 19 | \code{sys.argv[1:]}). |
| 20 | The second argument is the string of option letters that the |
| 21 | script wants to recognize, with options that require an argument |
| 22 | followed by a colon (i.e., the same format that \UNIX{} |
| 23 | \code{getopt()} |
| 24 | uses). |
| 25 | The return value consists of two elements: the first is a list of |
| 26 | option-and-value pairs; the second is the list of program arguments |
| 27 | left after the option list was stripped (this is a trailing slice of the |
| 28 | first argument). |
| 29 | Each option-and-value pair returned has the option as its first element, |
| 30 | prefixed with a hyphen (e.g., |
| 31 | \code{'-x'}), |
| 32 | and the option argument as its second element, or an empty string if the |
| 33 | option has no argument. |
| 34 | The options occur in the list in the same order in which they were |
| 35 | found, thus allowing multiple occurrences. |
| 36 | Example: |
| 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 | |
| 51 | The exception |
| 52 | \code{getopt.error = 'getopt error'} |
| 53 | is raised when an unrecognized option is found in the argument list or |
| 54 | when an option requiring an argument is given none. |
| 55 | The argument to the exception is a string indicating the cause of the |
| 56 | error. |