Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 1 | # 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 | |
| 21 | error = 'getopt error' |
| 22 | |
| 23 | def getopt(args, options): |
| 24 | list = [] |
Guido van Rossum | 70083de | 1992-01-09 11:37:07 +0000 | [diff] [blame] | 25 | while args and args[0][:1] == '-' and args[0] <> '-': |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 26 | if args[0] == '--': |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 27 | 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 Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 33 | if optstring == '': |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 34 | 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 | |
| 43 | def classify(opt, options): # Helper to check type of option |
| 44 | for i in range(len(options)): |
Guido van Rossum | bdfcfcc | 1992-01-01 19:35:13 +0000 | [diff] [blame] | 45 | if opt == options[i] <> ':': |
| 46 | return options[i+1:i+2] == ':' |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 47 | raise error, 'option -' + opt + ' not recognized' |