home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Lib / getopt.py < prev    next >
Text File  |  2000-12-21  |  5KB  |  138 lines

  1. """Parser for command line options.
  2.  
  3. This module helps scripts to parse the command line arguments in
  4. sys.argv.  It supports the same conventions as the Unix getopt()
  5. function (including the special meanings of arguments of the form `-'
  6. and `--').  Long options similar to those supported by GNU software
  7. may be used as well via an optional third argument.  This module
  8. provides a single function and an exception:
  9.  
  10. getopt() -- Parse command line options
  11. GetoptError -- exception (class) raised with 'opt' attribute, which is the
  12. option involved with the exception.
  13. """
  14.  
  15. # Long option support added by Lars Wirzenius <liw@iki.fi>.
  16.  
  17. # Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
  18. # to class-based exceptions.
  19.  
  20. class GetoptError(Exception):
  21.     opt = ''
  22.     msg = ''
  23.     def __init__(self, *args):
  24.         self.args = args
  25.         if len(args) == 1:
  26.             self.msg = args[0]
  27.         elif len(args) == 2:
  28.             self.msg = args[0]
  29.             self.opt = args[1]
  30.  
  31.     def __str__(self):
  32.         return self.msg
  33.  
  34. error = GetoptError # backward compatibility
  35.  
  36. def getopt(args, shortopts, longopts = []):
  37.     """getopt(args, options[, long_options]) -> opts, args
  38.  
  39.     Parses command line options and parameter list.  args is the
  40.     argument list to be parsed, without the leading reference to the
  41.     running program.  Typically, this means "sys.argv[1:]".  shortopts
  42.     is the string of option letters that the script wants to
  43.     recognize, with options that require an argument followed by a
  44.     colon (i.e., the same format that Unix getopt() uses).  If
  45.     specified, longopts is a list of strings with the names of the
  46.     long options which should be supported.  The leading '--'
  47.     characters should not be included in the option name.  Options
  48.     which require an argument should be followed by an equal sign
  49.     ('=').
  50.  
  51.     The return value consists of two elements: the first is a list of
  52.     (option, value) pairs; the second is the list of program arguments
  53.     left after the option list was stripped (this is a trailing slice
  54.     of the first argument).  Each option-and-value pair returned has
  55.     the option as its first element, prefixed with a hyphen (e.g.,
  56.     '-x'), and the option argument as its second element, or an empty
  57.     string if the option has no argument.  The options occur in the
  58.     list in the same order in which they were found, thus allowing
  59.     multiple occurrences.  Long and short options may be mixed.
  60.  
  61.     """
  62.  
  63.     opts = []
  64.     if type(longopts) == type(""):
  65.         longopts = [longopts]
  66.     else:
  67.         longopts = list(longopts)
  68.     longopts.sort()
  69.     while args and args[0][:1] == '-' and args[0] != '-':
  70.         if args[0] == '--':
  71.             args = args[1:]
  72.             break
  73.         if args[0][:2] == '--':
  74.             opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
  75.         else:
  76.             opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  77.  
  78.     return opts, args
  79.  
  80. def do_longs(opts, opt, longopts, args):
  81.     try:
  82.         i = opt.index('=')
  83.         opt, optarg = opt[:i], opt[i+1:]
  84.     except ValueError:
  85.         optarg = None
  86.  
  87.     has_arg, opt = long_has_args(opt, longopts)
  88.     if has_arg:
  89.         if optarg is None:
  90.             if not args:
  91.                 raise GetoptError('option --%s requires argument' % opt, opt)
  92.             optarg, args = args[0], args[1:]
  93.     elif optarg:
  94.         raise GetoptError('option --%s must not have an argument' % opt, opt)
  95.     opts.append(('--' + opt, optarg or ''))
  96.     return opts, args
  97.  
  98. # Return:
  99. #   has_arg?
  100. #   full option name
  101. def long_has_args(opt, longopts):
  102.     optlen = len(opt)
  103.     for i in range(len(longopts)):
  104.         x, y = longopts[i][:optlen], longopts[i][optlen:]
  105.         if opt != x:
  106.             continue
  107.         if y != '' and y != '=' and i+1 < len(longopts):
  108.             if opt == longopts[i+1][:optlen]:
  109.                 raise GetoptError('option --%s not a unique prefix' % opt, opt)
  110.         if longopts[i][-1:] in ('=', ):
  111.             return 1, longopts[i][:-1]
  112.         return 0, longopts[i]
  113.     raise GetoptError('option --%s not recognized' % opt, opt)
  114.  
  115. def do_shorts(opts, optstring, shortopts, args):
  116.     while optstring != '':
  117.         opt, optstring = optstring[0], optstring[1:]
  118.         if short_has_arg(opt, shortopts):
  119.             if optstring == '':
  120.                 if not args:
  121.                     raise GetoptError('option -%s requires argument' % opt, opt)
  122.                 optstring, args = args[0], args[1:]
  123.             optarg, optstring = optstring, ''
  124.         else:
  125.             optarg = ''
  126.         opts.append(('-' + opt, optarg))
  127.     return opts, args
  128.  
  129. def short_has_arg(opt, shortopts):
  130.     for i in range(len(shortopts)):
  131.         if opt == shortopts[i] != ':':
  132.             return shortopts[i+1:i+2] == ':'
  133.     raise GetoptError('option -%s not recognized' % opt, opt)
  134.  
  135. if __name__ == '__main__':
  136.     import sys
  137.     print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
  138.