blob: 1bc42bd6a62ed769abe2561e9ca2159d3c54989b [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""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
Guido van Rossum80c33e51999-12-21 22:38:40 +000011GetoptError -- exception (class) raised with 'opt' attribute, which is the
12option involved with the exception.
Guido van Rossum6d060941998-11-17 04:16:37 +000013"""
Guido van Rossum1550ff71996-09-11 19:43:52 +000014
Guido van Rossum6d060941998-11-17 04:16:37 +000015# Long option support added by Lars Wirzenius <liw@iki.fi>.
Guido van Rossumc6360141990-10-13 19:23:40 +000016
Fred Drakea395ced2000-02-25 16:14:08 +000017# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
18# to class-based exceptions.
19
Guido van Rossum80c33e51999-12-21 22:38:40 +000020class GetoptError(Exception):
21 opt = ''
22 msg = ''
Fred Drakee1fd5262001-01-08 15:39:32 +000023 def __init__(self, msg, opt):
24 self.msg = msg
25 self.opt = opt
26 Exception.__init__(self, msg, opt)
Guido van Rossum80c33e51999-12-21 22:38:40 +000027
28 def __str__(self):
29 return self.msg
30
31error = GetoptError # backward compatibility
Guido van Rossumc6360141990-10-13 19:23:40 +000032
Guido van Rossum2c349bb1996-09-09 15:48:24 +000033def getopt(args, shortopts, longopts = []):
Guido van Rossum6d060941998-11-17 04:16:37 +000034 """getopt(args, options[, long_options]) -> opts, args
35
36 Parses command line options and parameter list. args is the
37 argument list to be parsed, without the leading reference to the
38 running program. Typically, this means "sys.argv[1:]". shortopts
39 is the string of option letters that the script wants to
40 recognize, with options that require an argument followed by a
41 colon (i.e., the same format that Unix getopt() uses). If
42 specified, longopts is a list of strings with the names of the
43 long options which should be supported. The leading '--'
44 characters should not be included in the option name. Options
45 which require an argument should be followed by an equal sign
46 ('=').
47
48 The return value consists of two elements: the first is a list of
49 (option, value) pairs; the second is the list of program arguments
50 left after the option list was stripped (this is a trailing slice
51 of the first argument). Each option-and-value pair returned has
52 the option as its first element, prefixed with a hyphen (e.g.,
53 '-x'), and the option argument as its second element, or an empty
54 string if the option has no argument. The options occur in the
55 list in the same order in which they were found, thus allowing
56 multiple occurrences. Long and short options may be mixed.
57
58 """
59
60 opts = []
61 if type(longopts) == type(""):
62 longopts = [longopts]
63 else:
64 longopts = list(longopts)
Tim Petersdd699b62000-12-27 08:05:05 +000065 while args and args[0].startswith('-') and args[0] != '-':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000066 if args[0] == '--':
67 args = args[1:]
68 break
69 if args[0][:2] == '--':
Guido van Rossum6d060941998-11-17 04:16:37 +000070 opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000071 else:
Guido van Rossum6d060941998-11-17 04:16:37 +000072 opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
Guido van Rossumc6360141990-10-13 19:23:40 +000073
Guido van Rossum6d060941998-11-17 04:16:37 +000074 return opts, args
Guido van Rossum2c349bb1996-09-09 15:48:24 +000075
Guido van Rossum6d060941998-11-17 04:16:37 +000076def do_longs(opts, opt, longopts, args):
Guido van Rossum1550ff71996-09-11 19:43:52 +000077 try:
Fred Drakea395ced2000-02-25 16:14:08 +000078 i = opt.index('=')
Guido van Rossum1550ff71996-09-11 19:43:52 +000079 except ValueError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000080 optarg = None
Tim Petersdd699b62000-12-27 08:05:05 +000081 else:
82 opt, optarg = opt[:i], opt[i+1:]
Guido van Rossum2c349bb1996-09-09 15:48:24 +000083
Guido van Rossum1550ff71996-09-11 19:43:52 +000084 has_arg, opt = long_has_args(opt, longopts)
85 if has_arg:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 if optarg is None:
87 if not args:
Guido van Rossum80c33e51999-12-21 22:38:40 +000088 raise GetoptError('option --%s requires argument' % opt, opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000089 optarg, args = args[0], args[1:]
Guido van Rossum1550ff71996-09-11 19:43:52 +000090 elif optarg:
Guido van Rossum80c33e51999-12-21 22:38:40 +000091 raise GetoptError('option --%s must not have an argument' % opt, opt)
Guido van Rossum6d060941998-11-17 04:16:37 +000092 opts.append(('--' + opt, optarg or ''))
93 return opts, args
Guido van Rossum2c349bb1996-09-09 15:48:24 +000094
95# Return:
96# has_arg?
97# full option name
98def long_has_args(opt, longopts):
Tim Petersd31b6322000-12-29 02:17:56 +000099 possibilities = [o for o in longopts if o.startswith(opt)]
100 if not possibilities:
Tim Petersdd699b62000-12-27 08:05:05 +0000101 raise GetoptError('option --%s not recognized' % opt, opt)
Tim Petersdd699b62000-12-27 08:05:05 +0000102 # Is there an exact match?
103 if opt in possibilities:
104 return 0, opt
105 elif opt + '=' in possibilities:
106 return 1, opt
107 # No exact match, so better be unique.
108 if len(possibilities) > 1:
109 # XXX since possibilities contains all valid continuations, might be
110 # nice to work them into the error msg
111 raise GetoptError('option --%s not a unique prefix' % opt, opt)
112 assert len(possibilities) == 1
113 unique_match = possibilities[0]
114 has_arg = unique_match.endswith('=')
115 if has_arg:
116 unique_match = unique_match[:-1]
117 return has_arg, unique_match
Guido van Rossum2c349bb1996-09-09 15:48:24 +0000118
Guido van Rossum6d060941998-11-17 04:16:37 +0000119def do_shorts(opts, optstring, shortopts, args):
Guido van Rossum1550ff71996-09-11 19:43:52 +0000120 while optstring != '':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000121 opt, optstring = optstring[0], optstring[1:]
122 if short_has_arg(opt, shortopts):
123 if optstring == '':
124 if not args:
Guido van Rossum80c33e51999-12-21 22:38:40 +0000125 raise GetoptError('option -%s requires argument' % opt, opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000126 optstring, args = args[0], args[1:]
127 optarg, optstring = optstring, ''
128 else:
129 optarg = ''
Guido van Rossum6d060941998-11-17 04:16:37 +0000130 opts.append(('-' + opt, optarg))
131 return opts, args
Guido van Rossum2c349bb1996-09-09 15:48:24 +0000132
133def short_has_arg(opt, shortopts):
Guido van Rossum1550ff71996-09-11 19:43:52 +0000134 for i in range(len(shortopts)):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 if opt == shortopts[i] != ':':
136 return shortopts[i+1:i+2] == ':'
Guido van Rossum80c33e51999-12-21 22:38:40 +0000137 raise GetoptError('option -%s not recognized' % opt, opt)
Guido van Rossum2c349bb1996-09-09 15:48:24 +0000138
139if __name__ == '__main__':
Guido van Rossum1550ff71996-09-11 19:43:52 +0000140 import sys
141 print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])