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