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