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