1 # module getopt -- Standard command line processing.
3 # Function getopt.getopt() has a different interface but provides the
4 # same functionality as the Unix getopt() function.
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).
11 # It raises the exception getopt.error with a string argument if it
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).
21 error
= 'getopt error'
23 def getopt(args
, options
):
25 while args
and args
[0][:1] == '-' and args
[0] <> '-':
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
35 raise error
, 'option -' + opt
+ ' requires argument'
36 optstring
, args
= args
[0], args
[1:]
37 optarg
, optstring
= optstring
, ''
40 list.append('-' + opt
, optarg
)
43 def classify(opt
, options
): # Helper to check type of option
44 for i
in range(len(options
)):
45 if opt
== options
[i
] <> ':':
46 return options
[i
+1:i
+2] == ':'
47 raise error
, 'option -' + opt
+ ' not recognized'