home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.6)
-
- __author__ = 'Bill Bumgarner <bbum@friday.com>'
- __license__ = 'MIT'
- __version__ = '1.2'
- import re
- import string
- import sys
- import types
-
- class Error(Exception):
- pass
-
-
- class ArgumentError(Error):
- pass
-
-
- class SpecificationError(Error):
- pass
-
-
- class TerminationError(Error):
- pass
-
- specificationExpr = re.compile('(?P<required>.)(?P<type>.)(?P<multi>@?)')
- ArgRequired = 'Requires an Argument'
- ArgOptional = 'Argument Optional'
- StringArgType = 'String Argument Type'
- IntegerArgType = 'Integer Argument Type'
- RealArgType = 'Real Argument Type'
- BooleanArgType = 'Boolean Argument Type'
- GenericArgType = 'Generic Argument Type'
- ConversionFunctions = {
- StringArgType: (lambda x: x),
- IntegerArgType: string.atoi,
- RealArgType: string.atof,
- BooleanArgType: (lambda x: x),
- GenericArgType: (lambda x: x) }
-
- class DPyGetOpt:
-
- def __init__(self, spec = None, terminators = [
- '--']):
- self.allowAbbreviations = 1
- self.freeValues = []
- self.ignoreCase = 0
- self.needsParse = 0
- self.optionNames = { }
- self.optionStartExpr = None
- self.optionTuples = []
- self.optionValues = { }
- self.orderMixed = 0
- self.posixCompliance = 0
- self.spec = []
- self.terminators = terminators
- self.termValues = []
- self.terminator = None
- self.setPosixCompliance()
- self.setIgnoreCase()
- self.setAllowAbbreviations()
- if spec:
- self.parseConfiguration(spec)
-
-
-
- def setPosixCompliance(self, aFlag = 0):
- self.posixCompliance = aFlag
- self.needsParse = 1
- if self.posixCompliance:
- self.optionStartExpr = re.compile('(--|-)(?P<option>[A-Za-z0-9_-]+)(?P<arg>=.*)?')
- self.orderMixed = 0
- else:
- self.optionStartExpr = re.compile('(--|-|\\+)(?P<option>[A-Za-z0-9_-]+)(?P<arg>=.*)?')
- self.orderMixed = 1
-
-
- def isPosixCompliant(self):
- return self.posixCompliance
-
-
- def setIgnoreCase(self, aFlag = 1):
- self.needsParse = 1
- self.ignoreCase = aFlag
-
-
- def ignoreCase(self):
- return self.ignoreCase
-
-
- def setAllowAbbreviations(self, aFlag = 1):
- self.allowAbbreviations = aFlag
-
-
- def willAllowAbbreviations(self):
- return self.allowAbbreviations
-
-
- def addTerminator(self, newTerm):
- self.terminators = self.terminators + [
- newTerm]
-
-
- def _addOption(self, oTuple):
- (type, mode, default, multi) = (name,)
- realName = oTuple
- if self.optionNames.has_key(name):
- if realName:
- raise SpecificationError("Alias '" + name + "' for '" + realName + "' already used for another option or alias.")
- realName
- raise SpecificationError("Option named '" + name + "' specified more than once. Specification: " + option)
- self.optionNames.has_key(name)
- self.optionNames[name] = self.tupleIndex
- self.tupleIndex = self.tupleIndex + 1
- self.optionTuples = self.optionTuples + [
- oTuple]
- if type == BooleanArgType:
- alias = 'no' + name
- specTuple = (type, mode, 0, multi)
- oTuple = (alias, specTuple, name)
- if self.optionNames.has_key(alias):
- if realName:
- raise SpecificationError("Negated alias '" + name + "' for '" + realName + "' already used for another option or alias.")
- realName
- raise SpecificationError("Negated option named '" + name + "' specified more than once. Specification: " + option)
- self.optionNames.has_key(alias)
- self.optionNames[alias] = self.tupleIndex
- self.tupleIndex = self.tupleIndex + 1
- self.optionTuples = self.optionTuples + [
- oTuple]
-
-
-
- def addOptionConfigurationTuple(self, oTuple):
- (name, argSpec, realName) = oTuple
- if self.ignoreCase:
- name = string.lower(name)
- if realName:
- realName = string.lower(realName)
- else:
- realName = name
- oTuple = (name, argSpec, realName)
-
- self._addOption(oTuple)
-
-
- def addOptionConfigurationTuples(self, oTuple):
- if type(oTuple) is ListType:
- for t in oTuple:
- self.addOptionConfigurationTuple(t)
-
- else:
- self.addOptionConfigurationTuple(oTuple)
-
-
- def parseConfiguration(self, spec):
- self.spec = spec
- self.optionTuples = []
- self.optionNames = { }
- self.tupleIndex = 0
- tupleIndex = 0
- splitExpr = re.compile('(?P<names>\\w+[-A-Za-z0-9|]*)?(?P<spec>!|[=:][infs]@?)?')
- for option in spec:
- if self.ignoreCase:
- option = string.lower(option)
-
- match = splitExpr.match(option)
- if match is None:
- raise SpecificationError('Invalid specification {' + option + '}')
- match is None
- names = match.group('names')
- specification = match.group('spec')
- nlist = string.split(names, '|')
- name = nlist[0]
- aliases = nlist[1:]
- if not specification:
- argType = GenericArgType
- argMode = None
- argDefault = 1
- argMultiple = 0
- elif specification == '!':
- argType = BooleanArgType
- argMode = None
- argDefault = 1
- argMultiple = 0
- else:
- match = specificationExpr.match(specification)
- if match is None:
- raise SpecificationError("Invalid configuration for option '" + option + "'")
- match is None
- required = match.group('required')
- if required == '=':
- argMode = ArgRequired
- elif required == ':':
- argMode = ArgOptional
- else:
- raise SpecificationError("Unknown requirement configuration '" + required + "'")
- type = (required == '=').group('type')
- if type == 's':
- argType = StringArgType
- argDefault = ''
- elif type == 'i':
- argType = IntegerArgType
- argDefault = 1
- elif type == 'f' or type == 'n':
- argType = RealArgType
- argDefault = 1
- else:
- raise SpecificationError("Unknown type specifier '" + type + "'")
- if (type == 'n').group('multi') == '@':
- argMultiple = 1
- else:
- argMultiple = 0
- specTuple = (argType, argMode, argDefault, argMultiple)
- oTuple = (name, specTuple, name)
- self._addOption(oTuple)
- for alias in aliases:
- if self.ignoreCase:
- alias = string.lower(alias)
-
- oTuple = (alias, specTuple, name)
- self._addOption(oTuple)
-
-
- self.needsParse = 0
-
-
- def _getArgTuple(self, argName):
-
- try:
- tupleIndex = self.optionNames[argName]
- return [
- self.optionTuples[tupleIndex]]
- except KeyError:
- if not self.allowAbbreviations:
- return None
- except:
- self.allowAbbreviations
-
- argExpr = re.compile('^' + argName)
- tuples = filter((lambda x, argExpr = argExpr: argExpr.search(x[0]) is not None), self.optionTuples)
- if not len(tuples):
- return None
- return tuples
-
-
- def _isTerminator(self, optionName):
- if optionName in self.terminators:
- self.terminator = optionName
- elif not self.allowAbbreviations:
- return None
- terms = filter((lambda x, on = optionName: string.find(x, on) == 0), self.terminators)
- if not len(terms):
- return None
- if len(terms) > 1:
- raise TerminationError("Ambiguous terminator '" + optionName + "' matches " + repr(terms))
- len(terms) > 1
- self.terminator = terms[0]
- return self.terminator
-
-
- def processArguments(self, args = None):
- if hasattr(sys, 'argv') and args == sys.argv:
- args = sys.argv[1:]
-
- max = len(args)
- self.freeValues = []
- self.optionValues = { }
- index = 0
- self.terminator = None
- self.termValues = []
- while index < max:
- arg = args[index]
- index = index + 1
- if self._isTerminator(arg):
- self.freeValues = self.freeValues + args[index:]
- self.termValues = args[index:]
- return None
- match = self.optionStartExpr.match(arg)
- optName = match.group('option')
- nextArg = match.group('arg')
- if nextArg:
- nextArg = nextArg[1:]
- index = index - 1
- else:
-
- try:
- nextArg = args[index]
- except:
- nextArg = None
-
- if self.ignoreCase:
- optName = string.lower(optName)
-
- tuples = self._getArgTuple(optName)
- if tuples == None:
- raise ArgumentError("Illegal option '" + arg + "'")
- tuples == None
- if len(tuples) > 1:
- raise ArgumentError("Ambiguous option '" + arg + "'; matches " + repr(map((lambda x: x[0]), tuples)))
- len(tuples) > 1
- config = tuples[0]
- (fullName, spec, realName) = config
- (optType, optMode, optDefault, optMultiple) = spec
- if optMode == ArgRequired:
- if not nextArg or self._isTerminator(nextArg):
- raise ArgumentError("Option '" + arg + "' requires an argument of type " + optType)
- self._isTerminator(nextArg)
-
- if not (optMode == None) and nextArg and not self._isTerminator(nextArg):
-
- try:
- func = ConversionFunctions[optType]
-
- try:
- optionValue = func(nextArg)
- index = index + 1
- except:
- if optMode == ArgRequired:
- raise ArgumentError("Invalid argument to option '" + arg + "'; should be '" + optType + "'")
- optMode == ArgRequired
- optionValue = optDefault
-
- except ArgumentError:
- raise
- except:
- None<EXCEPTION MATCH>ArgumentError
- raise ArgumentError('(' + arg + ") Conversion function for '" + optType + "' not found.")
-
-
- None<EXCEPTION MATCH>ArgumentError
- optionValue = optDefault
- if optMultiple:
-
- try:
- self.optionValues[realName] = self.optionValues[realName] + [
- optionValue]
- self.optionValues[realName] = [
- optionValue]
-
- continue
- if self.isPosixCompliant and self.optionValues.has_key(realName):
- raise ArgumentError("Argument '" + arg + "' occurs multiple times.")
- self.optionValues.has_key(realName)
- self.optionValues[realName] = optionValue
-
-
- def valueForOption(self, optionName, defaultValue = None):
-
- try:
- optionValue = self.optionValues[optionName]
- except:
- optionValue = defaultValue
-
- return optionValue
-
-
- test_error = 'Test Run Amok!'
-
- def _test():
-
- try:
- DPyGetOpt([
- 'foo',
- 'bar=s',
- 'foo'])
- except Error:
- exc = None
- print "EXCEPTION (should be 'foo' already used..): %s" % exc
-
-
- try:
- DPyGetOpt([
- 'foo|bar|apple=s@',
- 'baz|apple!'])
- except Error:
- exc = None
- print 'EXCEPTION (should be duplicate alias/name error): %s' % exc
-
- x = DPyGetOpt([
- 'apple|atlas=i@',
- 'application|executable=f@'])
-
- try:
- x.processArguments([
- '-app',
- '29.3'])
- except Error:
- exc = None
- print 'EXCEPTION (should be ambiguous argument): %s' % exc
-
- x = DPyGetOpt([
- 'foo'], [
- 'antigravity',
- 'antithesis'])
-
- try:
- x.processArguments([
- '-foo',
- 'anti'])
- except Error:
- exc = None
- print 'EXCEPTION (should be ambiguous terminator): %s' % exc
-
- profile = [
- 'plain-option',
- 'boolean-option!',
- 'list-of-integers=i@',
- 'list-real-option|list-real-alias|list-real-pseudonym=f@',
- 'optional-string-option:s',
- 'abbreviated-string-list=s@']
- terminators = [
- 'terminator']
- args = [
- '-plain-option',
- '+noboolean-option',
- '--list-of-integers',
- '1',
- '+list-of-integers',
- '2',
- '-list-of-integers',
- '3',
- 'freeargone',
- '-list-real-option',
- '1.1',
- '+list-real-alias',
- '1.2',
- '--list-real-pseudonym',
- '1.3',
- 'freeargtwo',
- '-abbreviated-string-list',
- 'String1',
- '--abbreviated-s',
- 'String2',
- '-abbrev',
- 'String3',
- '-a',
- 'String4',
- '-optional-string-option',
- 'term',
- 'next option should look like an invalid arg',
- '-a']
- print 'Using profile: ' + repr(profile)
- print 'With terminator: ' + repr(terminators)
- print 'Processing arguments: ' + repr(args)
- go = DPyGetOpt(profile, terminators)
- go.processArguments(args)
- print 'Options (and values): ' + repr(go.optionValues)
- print 'free args: ' + repr(go.freeValues)
- print 'term args: ' + repr(go.termValues)
-
-