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