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