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