rest25/library/getopt.rst => rest262/library/getopt.rst
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
n12-the special meanings of arguments of the form '``-``' and '``-``\ ``-``'). Long
n12+the special meanings of arguments of the form '``-``' and '``--``').  Long
13options similar to those supported by GNU software may be used as well via an
n14-optional third argument. This module provides a single function and an
n14+optional third argument.
15+ 
16+A more convenient, flexible, and powerful alternative is the
17+:mod:`optparse` module.
18+ 
19+This module provides two functions and an
15exception:
n16- 
17-.. % That's to fool latex2html into leaving the two hyphens alone!
18
19
20.. function:: getopt(args, options[, long_options])
21
22   Parses command line options and parameter list.  *args* is the argument list to
23   be parsed, without the leading reference to the running program. Typically, this
24   means ``sys.argv[1:]``. *options* is the string of option letters that the
25   script wants to recognize, with options that require an argument followed by a
38   options, *options* should be an empty string.  Long options on the command line
39   can be recognized so long as they provide a prefix of the option name that
40   matches exactly one of the accepted options.  For example, if *long_options* is
41   ``['foo', 'frob']``, the option :option:`--fo` will match as :option:`--foo`,
42   but :option:`--f` will not match uniquely, so :exc:`GetoptError` will be raised.
43
44   The return value consists of two elements: the first is a list of ``(option,
45   value)`` pairs; the second is the list of program arguments left after the
n46-   option list was stripped (this is a trailing slice of *args*).  Each option-and-
n49+   option list was stripped (this is a trailing slice of *args*).  Each
47-   value pair returned has the option as its first element, prefixed with a hyphen
50+   option-and-value pair returned has the option as its first element, prefixed
48-   for short options (e.g., ``'-x'``) or two hyphens for long options (e.g.,
51+   with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
49-   ``'-``\ ``-long-option'``), and the option argument as its second element, or an
52+   options (e.g., ``'-``\ ``-long-option'``), and the option argument as its
50-   empty string if the option has no argument.  The options occur in the list in
53+   second element, or an empty string if the option has no argument.  The
51-   the same order in which they were found, thus allowing multiple occurrences.
54+   options occur in the list in the same order in which they were found, thus
52-   Long and short options may be mixed.
55+   allowing multiple occurrences.  Long and short options may be mixed.
53
54
55.. function:: gnu_getopt(args, options[, long_options])
56
57   This function works like :func:`getopt`, except that GNU style scanning mode is
58   used by default. This means that option and non-option arguments may be
59   intermixed. The :func:`getopt` function stops processing options as soon as a
60   non-option argument is encountered.
61
62   If the first character of the option string is '+', or if the environment
n63-   variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-
n66+   variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
64-   option argument is encountered.
67+   soon as a non-option argument is encountered.
65
66   .. versionadded:: 2.3
67
68
69.. exception:: GetoptError
70
71   This is raised when an unrecognized option is found in the argument list or when
72   an option requiring an argument is given none. The argument to the exception is
79   .. versionchanged:: 1.6
80      Introduced :exc:`GetoptError` as a synonym for :exc:`error`.
81
82
83.. exception:: error
84
85   Alias for :exc:`GetoptError`; for backward compatibility.
86
n87-An example using only Unix style options::
n90+An example using only Unix style options:
88
89   >>> import getopt
90   >>> args = '-a -b -cfoo -d bar a1 a2'.split()
91   >>> args
92   ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
93   >>> optlist, args = getopt.getopt(args, 'abc:d:')
94   >>> optlist
95   [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
96   >>> args
97   ['a1', 'a2']
98
n99-Using long option names is equally easy::
n102+Using long option names is equally easy:
100
101   >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
102   >>> args = s.split()
103   >>> args
104   ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
105   >>> optlist, args = getopt.getopt(args, 'x', [
106   ...     'condition=', 'output-file=', 'testing'])
107   >>> optlist
n108-   [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x',
n111+   [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
109-    '')]
110   >>> args
111   ['a1', 'a2']
112
113In a script, typical usage is something like this::
114
115   import getopt, sys
116
117   def main():
118       try:
119           opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
n120-       except getopt.GetoptError:
n122+       except getopt.GetoptError, err:
121           # print help information and exit:
n124+           print str(err) # will print something like "option -a not recognized"
122           usage()
123           sys.exit(2)
124       output = None
125       verbose = False
126       for o, a in opts:
127           if o == "-v":
128               verbose = True
n129-           if o in ("-h", "--help"):
n132+           elif o in ("-h", "--help"):
130               usage()
131               sys.exit()
n132-           if o in ("-o", "--output"):
n135+           elif o in ("-o", "--output"):
133               output = a
t137+           else:
138+               assert False, "unhandled option"
134       # ...
135
136   if __name__ == "__main__":
137       main()
138
139
140.. seealso::
141
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op