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