blob: 31b1fc8cea6f9793dc416f460e7133929b003128 [file] [log] [blame]
Guido van Rossum6d060941998-11-17 04:16:37 +00001"""Module getopt -- Parser for command line options.
Guido van Rossumc6360141990-10-13 19:23:40 +00002
Guido van Rossum6d060941998-11-17 04:16:37 +00003This module helps scripts to parse the command line arguments in
4sys.argv. It supports the same conventions as the Unix getopt()
5function (including the special meanings of arguments of the form `-'
6and `--'). Long options similar to those supported by GNU software
7may be used as well via an optional third argument. This module
8provides a single function and an exception:
Guido van Rossumc6360141990-10-13 19:23:40 +00009
Guido van Rossum6d060941998-11-17 04:16:37 +000010getopt() -- Parse command line options
11error -- Exception (string) raised when bad options are found
12"""
Guido van Rossum1550ff71996-09-11 19:43:52 +000013
Guido van Rossum6d060941998-11-17 04:16:37 +000014# Long option support added by Lars Wirzenius <liw@iki.fi>.
Guido van Rossumc6360141990-10-13 19:23:40 +000015
Guido van Rossum2c349bb1996-09-09 15:48:24 +000016import string
17
Guido van Rossum1550ff71996-09-11 19:43:52 +000018error = 'getopt.error'
Guido van Rossumc6360141990-10-13 19:23:40 +000019
Guido van Rossum2c349bb1996-09-09 15:48:24 +000020def getopt(args, shortopts, longopts = []):
Guido van Rossum6d060941998-11-17 04:16:37 +000021 """getopt(args, options[, long_options]) -> opts, args
22
23 Parses command line options and parameter list. args is the
24 argument list to be parsed, without the leading reference to the
25 running program. Typically, this means "sys.argv[1:]". shortopts
26 is the string of option letters that the script wants to
27 recognize, with options that require an argument followed by a
28 colon (i.e., the same format that Unix getopt() uses). If
29 specified, longopts is a list of strings with the names of the
30 long options which should be supported. The leading '--'
31 characters should not be included in the option name. Options
32 which require an argument should be followed by an equal sign
33 ('=').
34
35 The return value consists of two elements: the first is a list of
36 (option, value) pairs; the second is the list of program arguments
37 left after the option list was stripped (this is a trailing slice
38 of the first argument). Each option-and-value pair returned has
39 the option as its first element, prefixed with a hyphen (e.g.,
40 '-x'), and the option argument as its second element, or an empty
41 string if the option has no argument. The options occur in the
42 list in the same order in which they were found, thus allowing
43 multiple occurrences. Long and short options may be mixed.
44
45 """
46
47 opts = []
48 if type(longopts) == type(""):
49 longopts = [longopts]
50 else:
51 longopts = list(longopts)
Guido van Rossum1550ff71996-09-11 19:43:52 +000052 longopts.sort()
53 while args and args[0][:1] == '-' and args[0] != '-':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000054 if args[0] == '--':
55 args = args[1:]
56 break
57 if args[0][:2] == '--':
Guido van Rossum6d060941998-11-17 04:16:37 +000058 opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000059 else:
Guido van Rossum6d060941998-11-17 04:16:37 +000060 opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
Guido van Rossumc6360141990-10-13 19:23:40 +000061
Guido van Rossum6d060941998-11-17 04:16:37 +000062 return opts, args
Guido van Rossum2c349bb1996-09-09 15:48:24 +000063
Guido van Rossum6d060941998-11-17 04:16:37 +000064def do_longs(opts, opt, longopts, args):
Guido van Rossum1550ff71996-09-11 19:43:52 +000065 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000066 i = string.index(opt, '=')
67 opt, optarg = opt[:i], opt[i+1:]
Guido van Rossum1550ff71996-09-11 19:43:52 +000068 except ValueError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000069 optarg = None
Guido van Rossum2c349bb1996-09-09 15:48:24 +000070
Guido van Rossum1550ff71996-09-11 19:43:52 +000071 has_arg, opt = long_has_args(opt, longopts)
72 if has_arg:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000073 if optarg is None:
74 if not args:
75 raise error, 'option --%s requires argument' % opt
76 optarg, args = args[0], args[1:]
Guido van Rossum1550ff71996-09-11 19:43:52 +000077 elif optarg:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 raise error, 'option --%s must not have an argument' % opt
Guido van Rossum6d060941998-11-17 04:16:37 +000079 opts.append(('--' + opt, optarg or ''))
80 return opts, args
Guido van Rossum2c349bb1996-09-09 15:48:24 +000081
82# Return:
83# has_arg?
84# full option name
85def long_has_args(opt, longopts):
Guido van Rossum1550ff71996-09-11 19:43:52 +000086 optlen = len(opt)
87 for i in range(len(longopts)):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 x, y = longopts[i][:optlen], longopts[i][optlen:]
89 if opt != x:
90 continue
91 if y != '' and y != '=' and i+1 < len(longopts):
92 if opt == longopts[i+1][:optlen]:
93 raise error, 'option --%s not a unique prefix' % opt
94 if longopts[i][-1:] in ('=', ):
95 return 1, longopts[i][:-1]
96 return 0, longopts[i]
Guido van Rossum1550ff71996-09-11 19:43:52 +000097 raise error, 'option --' + opt + ' not recognized'
Guido van Rossum2c349bb1996-09-09 15:48:24 +000098
Guido van Rossum6d060941998-11-17 04:16:37 +000099def do_shorts(opts, optstring, shortopts, args):
Guido van Rossum1550ff71996-09-11 19:43:52 +0000100 while optstring != '':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 opt, optstring = optstring[0], optstring[1:]
102 if short_has_arg(opt, shortopts):
103 if optstring == '':
104 if not args:
105 raise error, 'option -%s requires argument' % opt
106 optstring, args = args[0], args[1:]
107 optarg, optstring = optstring, ''
108 else:
109 optarg = ''
Guido van Rossum6d060941998-11-17 04:16:37 +0000110 opts.append(('-' + opt, optarg))
111 return opts, args
Guido van Rossum2c349bb1996-09-09 15:48:24 +0000112
113def short_has_arg(opt, shortopts):
Guido van Rossum1550ff71996-09-11 19:43:52 +0000114 for i in range(len(shortopts)):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000115 if opt == shortopts[i] != ':':
116 return shortopts[i+1:i+2] == ':'
Guido van Rossum1550ff71996-09-11 19:43:52 +0000117 raise error, 'option -%s not recognized' % opt
Guido van Rossum2c349bb1996-09-09 15:48:24 +0000118
119if __name__ == '__main__':
Guido van Rossum1550ff71996-09-11 19:43:52 +0000120 import sys
121 print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])