blob: 7feaf9d525201ad07320dd65697d4a60b661a87b [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# module getopt -- Standard command line processing.
2
3# Function getopt.getopt() has a different interface but provides the
4# same functionality as the Unix getopt() function.
5
6# It has two arguments: the first should be argv[1:] (it doesn't want
7# the script name), the second the string of option letters as passed
8# to Unix getopt() (i.e., a string of allowable option letters, with
9# options requiring an argument followed by a colon).
10
11# It raises the exception getopt.error with a string argument if it
12# detects an error.
13
14# It returns two items:
15# (1) a list of pairs (option, option_argument) giving the options in
16# the order in which they were specified. (I'd use a dictionary
17# but applications may depend on option order or multiple
18# occurrences.) Boolean options have '' as option_argument.
19# (2) the list of remaining arguments (may be empty).
20
21error = 'getopt error'
22
23def getopt(args, options):
24 list = []
Guido van Rossum70083de1992-01-09 11:37:07 +000025 while args and args[0][:1] == '-' and args[0] <> '-':
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000026 if args[0] == '--':
Guido van Rossumc6360141990-10-13 19:23:40 +000027 args = args[1:]
28 break
29 optstring, args = args[0][1:], args[1:]
30 while optstring <> '':
31 opt, optstring = optstring[0], optstring[1:]
32 if classify(opt, options): # May raise exception as well
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000033 if optstring == '':
Guido van Rossumc6360141990-10-13 19:23:40 +000034 if not args:
35 raise error, 'option -' + opt + ' requires argument'
36 optstring, args = args[0], args[1:]
37 optarg, optstring = optstring, ''
38 else:
39 optarg = ''
40 list.append('-' + opt, optarg)
41 return list, args
42
43def classify(opt, options): # Helper to check type of option
44 for i in range(len(options)):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000045 if opt == options[i] <> ':':
46 return options[i+1:i+2] == ':'
Guido van Rossumc6360141990-10-13 19:23:40 +000047 raise error, 'option -' + opt + ' not recognized'