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