home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Lib / getopt.py < prev    next >
Text File  |  1993-12-29  |  2KB  |  48 lines

  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 = []
  25.     while args and args[0][:1] == '-' and args[0] <> '-':
  26.         if args[0] == '--':
  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
  33.                 if optstring == '':
  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)):
  45.     if opt == options[i] <> ':':
  46.         return options[i+1:i+2] == ':'
  47.     raise error, 'option -' + opt + ' not recognized'
  48.