home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / getopt.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  6.1 KB  |  163 lines

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