| Steven Bethard | 6d26569 | 2010-03-02 09:22:57 +0000 | [diff] [blame] | 1 | :mod:`getopt` --- C-style parser for command line options | 
 | 2 | ========================================================= | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3 |  | 
 | 4 | .. module:: getopt | 
| Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 5 |    :synopsis: Portable parser for command line options; support both short and | 
 | 6 |               long option names. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 7 |  | 
| Raymond Hettinger | 469271d | 2011-01-27 20:38:46 +0000 | [diff] [blame] | 8 | **Source code:** :source:`Lib/getopt.py` | 
 | 9 |  | 
 | 10 | -------------- | 
 | 11 |  | 
| Steven Bethard | 5971096 | 2010-05-24 03:21:08 +0000 | [diff] [blame] | 12 | .. note:: | 
 | 13 |    The :mod:`getopt` module is a parser for command line options whose API is | 
| Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 14 |    designed to be familiar to users of the C :c:func:`getopt` function. Users who | 
 | 15 |    are unfamiliar with the C :c:func:`getopt` function or who would like to write | 
| Steven Bethard | 5971096 | 2010-05-24 03:21:08 +0000 | [diff] [blame] | 16 |    less code and get better help and error messages should consider using the | 
 | 17 |    :mod:`argparse` module instead. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 |  | 
 | 19 | This module helps scripts to parse the command line arguments in ``sys.argv``. | 
| Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 20 | It supports the same conventions as the Unix :c:func:`getopt` function (including | 
| Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 21 | the special meanings of arguments of the form '``-``' and '``--``').  Long | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 22 | options similar to those supported by GNU software may be used as well via an | 
| Benjamin Peterson | ae5360b | 2008-09-08 23:05:23 +0000 | [diff] [blame] | 23 | optional third argument. | 
 | 24 |  | 
| Benjamin Peterson | ae5360b | 2008-09-08 23:05:23 +0000 | [diff] [blame] | 25 | This module provides two functions and an | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | exception: | 
 | 27 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 28 |  | 
| Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 29 | .. function:: getopt(args, shortopts, longopts=[]) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 30 |  | 
 | 31 |    Parses command line options and parameter list.  *args* is the argument list to | 
 | 32 |    be parsed, without the leading reference to the running program. Typically, this | 
| Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 33 |    means ``sys.argv[1:]``. *shortopts* is the string of option letters that the | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 34 |    script wants to recognize, with options that require an argument followed by a | 
| Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 35 |    colon (``':'``; i.e., the same format that Unix :c:func:`getopt` uses). | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 |  | 
 | 37 |    .. note:: | 
 | 38 |  | 
| Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 39 |       Unlike GNU :c:func:`getopt`, after a non-option argument, all further | 
| Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 40 |       arguments are considered also non-options. This is similar to the way | 
 | 41 |       non-GNU Unix systems work. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 |  | 
| Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 43 |    *longopts*, if specified, must be a list of strings with the names of the | 
| Georg Brandl | 81ac1ce | 2007-08-31 17:17:17 +0000 | [diff] [blame] | 44 |    long options which should be supported.  The leading ``'--'`` characters | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 45 |    should not be included in the option name.  Long options which require an | 
| Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 46 |    argument should be followed by an equal sign (``'='``).  Optional arguments | 
 | 47 |    are not supported.  To accept only long options, *shortopts* should be an | 
 | 48 |    empty string.  Long options on the command line can be recognized so long as | 
 | 49 |    they provide a prefix of the option name that matches exactly one of the | 
 | 50 |    accepted options.  For example, if *longopts* is ``['foo', 'frob']``, the | 
| Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 51 |    option ``--fo`` will match as ``--foo``, but ``--f`` will | 
| Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 52 |    not match uniquely, so :exc:`GetoptError` will be raised. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 53 |  | 
 | 54 |    The return value consists of two elements: the first is a list of ``(option, | 
 | 55 |    value)`` pairs; the second is the list of program arguments left after the | 
 | 56 |    option list was stripped (this is a trailing slice of *args*).  Each | 
 | 57 |    option-and-value pair returned has the option as its first element, prefixed | 
 | 58 |    with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long | 
| Georg Brandl | 81ac1ce | 2007-08-31 17:17:17 +0000 | [diff] [blame] | 59 |    options (e.g., ``'--long-option'``), and the option argument as its | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 60 |    second element, or an empty string if the option has no argument.  The | 
 | 61 |    options occur in the list in the same order in which they were found, thus | 
 | 62 |    allowing multiple occurrences.  Long and short options may be mixed. | 
 | 63 |  | 
 | 64 |  | 
| Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 65 | .. function:: gnu_getopt(args, shortopts, longopts=[]) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 66 |  | 
 | 67 |    This function works like :func:`getopt`, except that GNU style scanning mode is | 
 | 68 |    used by default. This means that option and non-option arguments may be | 
 | 69 |    intermixed. The :func:`getopt` function stops processing options as soon as a | 
 | 70 |    non-option argument is encountered. | 
 | 71 |  | 
| Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 72 |    If the first character of the option string is ``'+'``, or if the environment | 
| Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 73 |    variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as | 
 | 74 |    soon as a non-option argument is encountered. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 75 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 76 |  | 
 | 77 | .. exception:: GetoptError | 
 | 78 |  | 
 | 79 |    This is raised when an unrecognized option is found in the argument list or when | 
 | 80 |    an option requiring an argument is given none. The argument to the exception is | 
 | 81 |    a string indicating the cause of the error.  For long options, an argument given | 
 | 82 |    to an option which does not require one will also cause this exception to be | 
 | 83 |    raised.  The attributes :attr:`msg` and :attr:`opt` give the error message and | 
 | 84 |    related option; if there is no specific option to which the exception relates, | 
 | 85 |    :attr:`opt` is an empty string. | 
 | 86 |  | 
| Georg Brandl | 55ac8f0 | 2007-09-01 13:51:09 +0000 | [diff] [blame] | 87 | .. XXX deprecated? | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | .. exception:: error | 
 | 89 |  | 
 | 90 |    Alias for :exc:`GetoptError`; for backward compatibility. | 
 | 91 |  | 
| Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 92 | An example using only Unix style options: | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 93 |  | 
 | 94 |    >>> import getopt | 
 | 95 |    >>> args = '-a -b -cfoo -d bar a1 a2'.split() | 
 | 96 |    >>> args | 
 | 97 |    ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] | 
 | 98 |    >>> optlist, args = getopt.getopt(args, 'abc:d:') | 
 | 99 |    >>> optlist | 
 | 100 |    [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] | 
 | 101 |    >>> args | 
 | 102 |    ['a1', 'a2'] | 
 | 103 |  | 
| Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 104 | Using long option names is equally easy: | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 105 |  | 
 | 106 |    >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' | 
 | 107 |    >>> args = s.split() | 
 | 108 |    >>> args | 
 | 109 |    ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] | 
 | 110 |    >>> optlist, args = getopt.getopt(args, 'x', [ | 
 | 111 |    ...     'condition=', 'output-file=', 'testing']) | 
 | 112 |    >>> optlist | 
| Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 113 |    [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 114 |    >>> args | 
 | 115 |    ['a1', 'a2'] | 
 | 116 |  | 
 | 117 | In a script, typical usage is something like this:: | 
 | 118 |  | 
 | 119 |    import getopt, sys | 
 | 120 |  | 
 | 121 |    def main(): | 
 | 122 |        try: | 
 | 123 |            opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) | 
 | 124 |        except getopt.GetoptError as err: | 
 | 125 |            # print help information and exit: | 
| Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 126 |            print(err) # will print something like "option -a not recognized" | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 127 |            usage() | 
 | 128 |            sys.exit(2) | 
 | 129 |        output = None | 
 | 130 |        verbose = False | 
 | 131 |        for o, a in opts: | 
 | 132 |            if o == "-v": | 
 | 133 |                verbose = True | 
 | 134 |            elif o in ("-h", "--help"): | 
 | 135 |                usage() | 
 | 136 |                sys.exit() | 
 | 137 |            elif o in ("-o", "--output"): | 
 | 138 |                output = a | 
 | 139 |            else: | 
 | 140 |                assert False, "unhandled option" | 
 | 141 |        # ... | 
 | 142 |  | 
 | 143 |    if __name__ == "__main__": | 
 | 144 |        main() | 
 | 145 |  | 
| Steven Bethard | 5971096 | 2010-05-24 03:21:08 +0000 | [diff] [blame] | 146 | Note that an equivalent command line interface could be produced with less code | 
 | 147 | and more informative help and error messages by using the :mod:`argparse` module:: | 
 | 148 |  | 
 | 149 |    import argparse | 
 | 150 |  | 
 | 151 |    if __name__ == '__main__': | 
 | 152 |        parser = argparse.ArgumentParser() | 
 | 153 |        parser.add_argument('-o', '--output') | 
 | 154 |        parser.add_argument('-v', dest='verbose', action='store_true') | 
 | 155 |        args = parser.parse_args() | 
 | 156 |        # ... do something with args.output ... | 
 | 157 |        # ... do something with args.verbose .. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 158 |  | 
 | 159 | .. seealso:: | 
 | 160 |  | 
| Steven Bethard | 5971096 | 2010-05-24 03:21:08 +0000 | [diff] [blame] | 161 |    Module :mod:`argparse` | 
 | 162 |       Alternative command line option and argument parsing library. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 163 |  |