def add_module(self, filename, abspath, modpath, code):
if modpath in self.modules:
- raise AttributeError, "%s already found in importer" % modpath
+ raise AttributeError("%s already found in importer" % modpath)
self.modules[modpath] = (filename, abspath, code)
if isinstance(c, MetaSimObject):
bTotal += 1
if bTotal > 1:
- raise TypeError, \
- "SimObjects do not support multiple inheritance"
+ raise TypeError(
+ "SimObjects do not support multiple inheritance")
base = bases[0]
def _set_keyword(cls, keyword, val, kwtype):
if not isinstance(val, kwtype):
- raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
- (keyword, type(val), kwtype)
+ raise TypeError('keyword %s has bad type %s (expecting %s)' % \
+ (keyword, type(val), kwtype))
if isinstance(val, FunctionType):
val = classmethod(val)
type.__setattr__(cls, keyword, val)
try:
hr_value = value
value = param.convert(value)
- except Exception, e:
+ except Exception as e:
msg = "%s\nError setting param %s.%s to %s\n" % \
(e, cls.__name__, name, value)
e.args = (msg, )
return
if isSimObjectOrSequence(value) and cls._instantiated:
- raise RuntimeError, \
+ raise RuntimeError(
"cannot set SimObject parameter '%s' after\n" \
" class %s has been instantiated or subclassed" \
- % (attr, cls.__name__)
+ % (attr, cls.__name__))
# check for param
param = cls._params.get(attr)
return
# no valid assignment... raise exception
- raise AttributeError, \
- "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
+ raise AttributeError(
+ "Class %s has no parameter \'%s\'" % (cls.__name__, attr))
def __getattr__(cls, attr):
if attr == 'cxx_class_path':
if cls._children.has_key(attr):
return cls._children[attr]
- raise AttributeError, \
- "object '%s' has no attribute '%s'" % (cls.__name__, attr)
+ raise AttributeError(
+ "object '%s' has no attribute '%s'" % (cls.__name__, attr))
def __str__(cls):
return cls.__name__
# no memo_dict: must be top-level clone operation.
# this is only allowed at the root of a hierarchy
if self._parent:
- raise RuntimeError, "attempt to clone object %s " \
+ raise RuntimeError("attempt to clone object %s " \
"not at the root of a tree (parent = %s)" \
- % (self, self._parent)
+ % (self, self._parent))
# create a new dict and use that.
memo_dict = {}
kwargs['_memo'] = memo_dict
err_string += "\n (C++ object is not yet constructed," \
" so wrapped C++ methods are unavailable.)"
- raise AttributeError, err_string
+ raise AttributeError(err_string)
# Set attribute (called on foo.attr = value when foo is an
# instance of class cls).
try:
hr_value = value
value = param.convert(value)
- except Exception, e:
+ except Exception as e:
msg = "%s\nError setting param %s.%s to %s\n" % \
(e, self.__class__.__name__, attr, value)
e.args = (msg, )
return
# no valid assignment... raise exception
- raise AttributeError, "Class %s has no parameter %s" \
- % (self.__class__.__name__, attr)
+ raise AttributeError("Class %s has no parameter %s" \
+ % (self.__class__.__name__, attr))
# this hack allows tacking a '[0]' onto parameters that may or may
def __getitem__(self, key):
if key == 0:
return self
- raise IndexError, "Non-zero index '%s' to SimObject" % key
+ raise IndexError("Non-zero index '%s' to SimObject" % key)
# this hack allows us to iterate over a SimObject that may
# not be a vector, so we can call a loop over it and get just one
if isinstance(child, ptype) and not visited:
if found_obj != None and child != found_obj:
- raise AttributeError, \
+ raise AttributeError(
'parent.any matched more than one: %s %s' % \
- (found_obj.path, child.path)
+ (found_obj.path, child.path))
found_obj = child
# search param space
for pname,pdesc in self._params.iteritems():
if issubclass(pdesc.ptype, ptype):
match_obj = self._values[pname]
if found_obj != None and found_obj != match_obj:
- raise AttributeError, \
+ raise AttributeError(
'parent.any matched more than one: %s and %s' % \
- (found_obj.path, match_obj.path)
+ (found_obj.path, match_obj.path))
found_obj = match_obj
return found_obj, found_obj != None
if not self._ccObject:
# Make sure this object is in the configuration hierarchy
if not self._parent and not isRoot(self):
- raise RuntimeError, "Attempt to instantiate orphan node"
+ raise RuntimeError("Attempt to instantiate orphan node")
# Cycles in the configuration hierarchy are not supported. This
# will catch the resulting recursion and stop.
self._ccObject = -1
params = self.getCCParams()
self._ccObject = params.create()
elif self._ccObject == -1:
- raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
- % self.path()
+ raise RuntimeError("%s: Cycle found in configuration hierarchy." \
+ % self.path())
return self._ccObject
def descendants(self):
def coerceSimObjectOrVector(value):
value = tryAsSimObjectOrVector(value)
if value is None:
- raise TypeError, "SimObject or SimObjectVector expected"
+ raise TypeError("SimObject or SimObjectVector expected")
return value
baseClasses = allClasses.copy()
elif len(args) == 2:
options, arguments = args
else:
- raise TypeError, "main() takes 0 or 2 arguments (%d given)" % len(args)
+ raise TypeError("main() takes 0 or 2 arguments (%d given)" % len(args))
m5.options = options
self.default = args[0]
self.desc = args[1]
else:
- raise TypeError, 'too many arguments'
+ raise TypeError('too many arguments')
if kwargs.has_key('desc'):
assert(not hasattr(self, 'desc'))
del kwargs['default']
if kwargs:
- raise TypeError, 'extra unknown kwargs %s' % kwargs
+ raise TypeError('extra unknown kwargs %s' % kwargs)
if not hasattr(self, 'desc'):
- raise TypeError, 'desc attribute missing'
+ raise TypeError('desc attribute missing')
def __getattr__(self, attr):
if attr == 'ptype':
self.ptype = ptype
return ptype
- raise AttributeError, "'%s' object has no attribute '%s'" % \
- (type(self).__name__, attr)
+ raise AttributeError("'%s' object has no attribute '%s'" % \
+ (type(self).__name__, attr))
def example_str(self):
if hasattr(self.ptype, "ex_str"):
class VectorParamValue(list):
__metaclass__ = MetaParamValue
def __setattr__(self, attr, value):
- raise AttributeError, \
- "Not allowed to set %s on '%s'" % (attr, type(self).__name__)
+ raise AttributeError("Not allowed to set %s on '%s'" % \
+ (attr, type(self).__name__))
def config_value(self):
return [v.config_value() for v in self]
def _check(self):
if not self.min <= self.value <= self.max:
- raise TypeError, 'Integer param out of bounds %d < %d < %d' % \
- (self.min, self.value, self.max)
+ raise TypeError('Integer param out of bounds %d < %d < %d' % \
+ (self.min, self.value, self.max))
def __init__(self, value):
if isinstance(value, str):
elif isinstance(value, (int, long, float, NumericParamValue)):
self.value = long(value)
else:
- raise TypeError, "Can't convert object of type %s to CheckedInt" \
- % type(value).__name__
+ raise TypeError("Can't convert object of type %s to CheckedInt" \
+ % type(value).__name__)
self._check()
def __call__(self, value):
if isinstance(value, (int, long, float, NumericParamValue, Float, str)):
self.value = float(value)
else:
- raise TypeError, "Can't convert object of type %s to Float" \
- % type(value).__name__
+ raise TypeError("Can't convert object of type %s to Float" \
+ % type(value).__name__)
def __call__(self, value):
self.__init__(value)
elif 'size' in kwargs:
self.end = self.start + Addr(kwargs.pop('size')) - 1
else:
- raise TypeError, "Either end or size must be specified"
+ raise TypeError("Either end or size must be specified")
# Now on to the optional bit
if 'intlvHighBit' in kwargs:
self.start = Addr(args[0])
self.end = Addr(args[1])
else:
- raise TypeError, "Too many arguments specified"
+ raise TypeError("Too many arguments specified")
if kwargs:
- raise TypeError, "Too many keywords: %s" % kwargs.keys()
+ raise TypeError("Too many keywords: %s" % list(kwargs.keys()))
def __str__(self):
return '%s:%s:%s:%s:%s:%s' \
return
if not isinstance(value, str):
- raise TypeError, "expected an ethernet address and didn't get one"
+ raise TypeError("expected an ethernet address and didn't get one")
bytes = value.split(':')
if len(bytes) != 6:
- raise TypeError, 'invalid ethernet address %s' % value
+ raise TypeError('invalid ethernet address %s' % value)
for byte in bytes:
if not 0 <= int(byte, base=16) <= 0xff:
- raise TypeError, 'invalid ethernet address %s' % value
+ raise TypeError('invalid ethernet address %s' % value)
self.value = value
def verifyIp(self):
if self.ip < 0 or self.ip >= (1 << 32):
- raise TypeError, "invalid ip address %#08x" % self.ip
+ raise TypeError("invalid ip address %#08x" % self.ip)
def getValue(self):
from _m5.net import IpAddress
elif elseVal:
setattr(self, key, elseVal)
else:
- raise TypeError, "No value set for %s" % key
+ raise TypeError("No value set for %s" % key)
if len(args) == 0:
handle_kwarg(self, kwargs, 'ip')
elif len(args) == 1:
if kwargs:
if not 'ip' in kwargs and not 'netmask' in kwargs:
- raise TypeError, "Invalid arguments"
+ raise TypeError("Invalid arguments")
handle_kwarg(self, kwargs, 'ip', args[0])
handle_kwarg(self, kwargs, 'netmask', args[0])
elif isinstance(args[0], IpNetmask):
self.ip = args[0]
self.netmask = args[1]
else:
- raise TypeError, "Too many arguments specified"
+ raise TypeError("Too many arguments specified")
if kwargs:
- raise TypeError, "Too many keywords: %s" % kwargs.keys()
+ raise TypeError("Too many keywords: %s" % list(kwargs.keys()))
self.verify()
def verify(self):
self.verifyIp()
if self.netmask < 0 or self.netmask > 32:
- raise TypeError, "invalid netmask %d" % netmask
+ raise TypeError("invalid netmask %d" % netmask)
def getValue(self):
from _m5.net import IpNetmask
elif elseVal:
setattr(self, key, elseVal)
else:
- raise TypeError, "No value set for %s" % key
+ raise TypeError("No value set for %s" % key)
if len(args) == 0:
handle_kwarg(self, kwargs, 'ip')
elif len(args) == 1:
if kwargs:
if not 'ip' in kwargs and not 'port' in kwargs:
- raise TypeError, "Invalid arguments"
+ raise TypeError("Invalid arguments")
handle_kwarg(self, kwargs, 'ip', args[0])
handle_kwarg(self, kwargs, 'port', args[0])
elif isinstance(args[0], IpWithPort):
self.ip = args[0]
self.port = args[1]
else:
- raise TypeError, "Too many arguments specified"
+ raise TypeError("Too many arguments specified")
if kwargs:
- raise TypeError, "Too many keywords: %s" % kwargs.keys()
+ raise TypeError("Too many keywords: %s" % list(kwargs.keys()))
self.verify()
def verify(self):
self.verifyIp()
if self.port < 0 or self.port > 0xffff:
- raise TypeError, "invalid port %d" % self.port
+ raise TypeError("invalid port %d" % self.port)
def getValue(self):
from _m5.net import IpWithPort
except ValueError:
pass
- raise ValueError, "Could not parse '%s' as a time" % value
+ raise ValueError("Could not parse '%s' as a time" % value)
class Time(ParamValue):
cxx_type = 'tm'
def __init__(cls, name, bases, init_dict):
if init_dict.has_key('map'):
if not isinstance(cls.map, dict):
- raise TypeError, "Enum-derived class attribute 'map' " \
- "must be of type dict"
+ raise TypeError("Enum-derived class attribute 'map' " \
+ "must be of type dict")
# build list of value strings from map
cls.vals = cls.map.keys()
cls.vals.sort()
elif init_dict.has_key('vals'):
if not isinstance(cls.vals, list):
- raise TypeError, "Enum-derived class attribute 'vals' " \
- "must be of type list"
+ raise TypeError("Enum-derived class attribute 'vals' " \
+ "must be of type list")
# build string->value map from vals sequence
cls.map = {}
for idx,val in enumerate(cls.vals):
cls.map[val] = idx
else:
- raise TypeError, "Enum-derived class must define "\
- "attribute 'map' or 'vals'"
+ raise TypeError("Enum-derived class must define "\
+ "attribute 'map' or 'vals'")
if cls.is_class:
cls.cxx_type = '%s' % name
def __init__(self, value):
if value not in self.map:
- raise TypeError, "Enum param got bad value '%s' (not in %s)" \
- % (value, self.vals)
+ raise TypeError("Enum param got bad value '%s' (not in %s)" \
+ % (value, self.vals))
self.value = value
def __call__(self, value):
return self
if attr == 'frequency':
return Frequency(self)
- raise AttributeError, "Latency object has no attribute '%s'" % attr
+ raise AttributeError("Latency object has no attribute '%s'" % attr)
def getValue(self):
if self.ticks or self.value == 0:
return self
if attr in ('latency', 'period'):
return Latency(self)
- raise AttributeError, "Frequency object has no attribute '%s'" % attr
+ raise AttributeError("Frequency object has no attribute '%s'" % attr)
# convert latency to ticks
def getValue(self):
return Frequency(self)
if attr in ('latency', 'period'):
return Latency(self)
- raise AttributeError, "Frequency object has no attribute '%s'" % attr
+ raise AttributeError("Frequency object has no attribute '%s'" % attr)
def getValue(self):
return self.period.getValue()
if attr == 'peerObj':
# shorthand for proxies
return self.peer.simobj
- raise AttributeError, "'%s' object has no attribute '%s'" % \
- (self.__class__.__name__, attr)
+ raise AttributeError("'%s' object has no attribute '%s'" % \
+ (self.__class__.__name__, attr))
# Full connection is symmetric (both ways). Called via
# SimObject.__setattr__ as a result of a port assignment, e.g.,
if other.peer is not self:
other.connect(self)
else:
- raise TypeError, \
- "assigning non-port reference '%s' to port '%s'" \
- % (other, self)
+ raise TypeError("assigning non-port reference '%s' to port '%s'" \
+ % (other, self))
# Allow a master/slave port pair to be spliced between
# a port and its connected peer. Useful operation for connecting
if not isinstance(new_master_peer, PortRef) or \
not isinstance(new_slave_peer, PortRef):
- raise TypeError, \
+ raise TypeError(
"Splicing non-port references '%s','%s' to port '%s'" % \
- (new_master_peer, new_slave_peer, self)
+ (new_master_peer, new_slave_peer, self))
old_peer = self.peer
if self.role == 'SLAVE':
# check that we connect a master to a slave
if self.role == peer.role:
- raise TypeError, \
- "cannot connect '%s' and '%s' due to identical role '%s'" \
- % (peer, self, self.role)
+ raise TypeError(
+ "cannot connect '%s' and '%s' due to identical role '%s'" % \
+ (peer, self, self.role))
if self.role == 'SLAVE':
# do nothing and let the master take care of it
def __getitem__(self, key):
if not isinstance(key, int):
- raise TypeError, "VectorPort index must be integer"
+ raise TypeError("VectorPort index must be integer")
if key >= len(self.elements):
# need to extend list
ext = [VectorPortElementRef(self.simobj, self.name, self.role, i)
def __setitem__(self, key, value):
if not isinstance(key, int):
- raise TypeError, "VectorPort index must be integer"
+ raise TypeError("VectorPort index must be integer")
self[key].connect(value)
def connect(self, other):
self.desc = args[0]
self.role = 'MASTER'
else:
- raise TypeError, 'wrong number of arguments'
+ raise TypeError('wrong number of arguments')
class SlavePort(Port):
# SlavePort("description")
self.desc = args[0]
self.role = 'SLAVE'
else:
- raise TypeError, 'wrong number of arguments'
+ raise TypeError('wrong number of arguments')
# VectorPort description object. Like Port, but represents a vector
# of connections (e.g., as on a XBar).
self.role = 'MASTER'
VectorPort.__init__(self, *args)
else:
- raise TypeError, 'wrong number of arguments'
+ raise TypeError('wrong number of arguments')
class VectorSlavePort(VectorPort):
# VectorSlavePort("description")
self.role = 'SLAVE'
VectorPort.__init__(self, *args)
else:
- raise TypeError, 'wrong number of arguments'
+ raise TypeError('wrong number of arguments')
# 'Fake' ParamDesc for Port references to assign to the _pdesc slot of
# proxy objects (via set_param_desc()) so that proxy error messages
def __setattr__(self, attr, value):
if not attr.startswith('_'):
- raise AttributeError, \
- "cannot set attribute '%s' on proxy object" % attr
+ raise AttributeError(
+ "cannot set attribute '%s' on proxy object" % attr)
super(BaseProxy, self).__setattr__(attr, value)
# support for multiplying proxies by constants or other proxies to
# other params
def __mul__(self, other):
if not (isinstance(other, (int, long, float)) or isproxy(other)):
- raise TypeError, \
- "Proxy multiplier must be a constant or a proxy to a param"
+ raise TypeError(
+ "Proxy multiplier must be a constant or a proxy to a param")
self._multipliers.append(other)
return self
# assert that we are multiplying with a compatible
# param
if not isinstance(multiplier, params.NumericParamValue):
- raise TypeError, \
- "Proxy multiplier must be a numerical param"
+ raise TypeError(
+ "Proxy multiplier must be a numerical param")
multiplier = multiplier.getValue()
result *= multiplier
return result
base._visited = False
if not done:
- raise AttributeError, \
- "Can't resolve proxy '%s' of type '%s' from '%s'" % \
- (self.path(), self._pdesc.ptype_str, base.path())
+ raise AttributeError(
+ "Can't resolve proxy '%s' of type '%s' from '%s'" % \
+ (self.path(), self._pdesc.ptype_str, base.path()))
if isinstance(result, BaseProxy):
if result == self:
- raise RuntimeError, "Cycle in unproxy"
+ raise RuntimeError("Cycle in unproxy")
result = result.unproxy(obj)
return self._mulcheck(result, base)
if attr.startswith('_'):
return super(AttrProxy, self).__getattr__(self, attr)
if hasattr(self, '_pdesc'):
- raise AttributeError, "Attribute reference on bound proxy"
+ raise AttributeError("Attribute reference on bound proxy")
# Return a copy of self rather than modifying self in place
# since self could be an indirect reference via a variable or
# parameter
# support indexing on proxies (e.g., Self.cpu[0])
def __getitem__(self, key):
if not isinstance(key, int):
- raise TypeError, "Proxy object requires integer index"
+ raise TypeError("Proxy object requires integer index")
if hasattr(self, '_pdesc'):
- raise AttributeError, "Index operation on bound proxy"
+ raise AttributeError("Index operation on bound proxy")
new_self = copy.deepcopy(self)
new_self._modifiers.append(key)
return new_self
def checkpoint(dir):
root = objects.Root.getInstance()
if not isinstance(root, objects.Root):
- raise TypeError, "Checkpoint must be called on a root object."
+ raise TypeError("Checkpoint must be called on a root object.")
drain()
memWriteback(root)
def _changeMemoryMode(system, mode):
if not isinstance(system, (objects.Root, objects.System)):
- raise TypeError, "Parameter of type '%s'. Must be type %s or %s." % \
- (type(system), objects.Root, objects.System)
+ raise TypeError("Parameter of type '%s'. Must be type %s or %s." % \
+ (type(system), objects.Root, objects.System))
if system.getMemoryMode() != mode:
system.setMemoryMode(mode)
else:
print("switching cpus")
if not isinstance(cpuList, list):
- raise RuntimeError, "Must pass a list to this function"
+ raise RuntimeError("Must pass a list to this function")
for item in cpuList:
if not isinstance(item, tuple) or len(item) != 2:
- raise RuntimeError, "List must have tuples of (oldCPU,newCPU)"
+ raise RuntimeError("List must have tuples of (oldCPU,newCPU)")
old_cpus = [old_cpu for old_cpu, new_cpu in cpuList]
new_cpus = [new_cpu for old_cpu, new_cpu in cpuList]
memory_mode_name = new_cpus[0].memory_mode()
for old_cpu, new_cpu in cpuList:
if not isinstance(old_cpu, objects.BaseCPU):
- raise TypeError, "%s is not of type BaseCPU" % old_cpu
+ raise TypeError("%s is not of type BaseCPU" % old_cpu)
if not isinstance(new_cpu, objects.BaseCPU):
- raise TypeError, "%s is not of type BaseCPU" % new_cpu
+ raise TypeError("%s is not of type BaseCPU" % new_cpu)
if new_cpu in old_cpu_set:
- raise RuntimeError, \
- "New CPU (%s) is in the list of old CPUs." % (old_cpu,)
+ raise RuntimeError(
+ "New CPU (%s) is in the list of old CPUs." % (old_cpu,))
if not new_cpu.switchedOut():
- raise RuntimeError, \
- "New CPU (%s) is already active." % (new_cpu,)
+ raise RuntimeError("New CPU (%s) is already active." % (new_cpu,))
if not new_cpu.support_take_over():
- raise RuntimeError, \
- "New CPU (%s) does not support CPU handover." % (old_cpu,)
+ raise RuntimeError(
+ "New CPU (%s) does not support CPU handover." % (old_cpu,))
if new_cpu.memory_mode() != memory_mode_name:
- raise RuntimeError, \
+ raise RuntimeError(
"%s and %s require different memory modes." % (new_cpu,
- new_cpus[0])
+ new_cpus[0]))
if old_cpu.switchedOut():
- raise RuntimeError, \
- "Old CPU (%s) is inactive." % (new_cpu,)
+ raise RuntimeError("Old CPU (%s) is inactive." % (new_cpu,))
if not old_cpu.support_take_over():
- raise RuntimeError, \
- "Old CPU (%s) does not support CPU handover." % (old_cpu,)
+ raise RuntimeError(
+ "Old CPU (%s) does not support CPU handover." % (old_cpu,))
try:
memory_mode = _memory_modes[memory_mode_name]
except KeyError:
- raise RuntimeError, "Invalid memory mode (%s)" % memory_mode_name
+ raise RuntimeError("Invalid memory mode (%s)" % memory_mode_name)
drain()
global fork_count
if not _m5.core.listenersDisabled():
- raise RuntimeError, "Can not fork a simulator with listeners enabled"
+ raise RuntimeError("Can not fork a simulator with listeners enabled")
drain()
try:
pid = os.fork()
- except OSError, e:
+ except OSError as e:
raise e
if pid == 0:
elif isinstance(ticksPerSecond, str):
tps = round(convert.anyToFrequency(ticksPerSecond))
else:
- raise TypeError, \
- "wrong type '%s' for ticksPerSecond" % type(ticksPerSecond)
+ raise TypeError(
+ "wrong type '%s' for ticksPerSecond" % type(ticksPerSecond))
_m5.core.setClockFrequency(int(tps))
# how big does a rounding error need to be before we warn about it?
import _m5.core
if not isinstance(value, float):
- raise TypeError, "can't convert '%s' to type tick" % type(value)
+ raise TypeError("can't convert '%s' to type tick" % type(value))
# once someone needs to convert to seconds, the global frequency
# had better be fixed
if not _m5.core.clockFrequencyFixed():
- raise AttributeError, \
- "In order to do conversions, the global frequency must be fixed"
+ raise AttributeError(
+ "In order to do conversions, the global frequency must be fixed")
if value == 0:
return 0
elif isinstance(v, str):
return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
else:
- raise TypeError
+ raise TypeError()
v1 = make_version_list(v1)
v2 = make_version_list(v2)
kwargs.setdefault('close_fds', True)
try:
subp = Popen(cmd, **kwargs)
- except Exception, e:
+ except Exception as e:
if no_exception:
return exception
raise
ensure that it is a directory"""
if os.path.exists(path):
if not os.path.isdir(path):
- raise AttributeError, "%s exists but is not directory" % path
+ raise AttributeError("%s exists but is not directory" % path)
else:
os.mkdir(path)
return self.args[item]
except ValueError:
pass
- raise IndexError, "Could not find '%s'" % item
+ raise IndexError("Could not find '%s'" % item)
class code_formatter_meta(type):
pattern = r"""
def assertStr(value):
if not isinstance(value, str):
- raise TypeError, "wrong type '%s' should be str" % type(value)
+ raise TypeError("wrong type '%s' should be str" % type(value))
# memory size configuration stuff
try:
return float(value)
except ValueError:
- raise ValueError, "cannot convert '%s' to %s" % \
- (value, target_type)
+ raise ValueError("cannot convert '%s' to %s" % \
+ (value, target_type))
value = value[:-len(units)]
value = toFloat(value, target_type, units, prefixes)
result = long(value)
if value != result:
- raise ValueError, "cannot convert '%s' to integer %s" % \
- (value, target_type)
+ raise ValueError("cannot convert '%s' to integer %s" % \
+ (value, target_type))
return result
"""result is a clock period"""
try:
return 1 / toFrequency(value)
- except ValueError, ZeroDivisionError:
+ except (ValueError, ZeroDivisionError):
pass
try:
except ValueError:
pass
- raise ValueError, "cannot convert '%s' to clock period" % value
+ raise ValueError("cannot convert '%s' to clock period" % value)
def anyToFrequency(value):
"""result is a clock period"""
try:
return 1 / toLatency(value)
- except ValueError, ZeroDivisionError:
+ except ValueError as ZeroDivisionError:
pass
- raise ValueError, "cannot convert '%s' to clock period" % value
+ raise ValueError("cannot convert '%s' to clock period" % value)
def toNetworkBandwidth(value):
return toMetricFloat(value, 'network bandwidth', 'bps')
def toIpAddress(value):
if not isinstance(value, str):
- raise TypeError, "wrong type '%s' should be str" % type(value)
+ raise TypeError("wrong type '%s' should be str" % type(value))
bytes = value.split('.')
if len(bytes) != 4:
- raise ValueError, 'invalid ip address %s' % value
+ raise ValueError('invalid ip address %s' % value)
for byte in bytes:
if not 0 <= int(byte) <= 0xff:
- raise ValueError, 'invalid ip address %s' % value
+ raise ValueError('invalid ip address %s' % value)
return (int(bytes[0]) << 24) | (int(bytes[1]) << 16) | \
(int(bytes[2]) << 8) | (int(bytes[3]) << 0)
def toIpNetmask(value):
if not isinstance(value, str):
- raise TypeError, "wrong type '%s' should be str" % type(value)
+ raise TypeError("wrong type '%s' should be str" % type(value))
(ip, netmask) = value.split('/')
ip = toIpAddress(ip)
netmaskParts = netmask.split('.')
if len(netmaskParts) == 1:
if not 0 <= int(netmask) <= 32:
- raise ValueError, 'invalid netmask %s' % netmask
+ raise ValueError('invalid netmask %s' % netmask)
return (ip, int(netmask))
elif len(netmaskParts) == 4:
netmaskNum = toIpAddress(netmask)
testVal |= (1 << (31 - i))
if testVal == netmaskNum:
return (ip, i + 1)
- raise ValueError, 'invalid netmask %s' % netmask
+ raise ValueError('invalid netmask %s' % netmask)
else:
- raise ValueError, 'invalid netmask %s' % netmask
+ raise ValueError('invalid netmask %s' % netmask)
def toIpWithPort(value):
if not isinstance(value, str):
- raise TypeError, "wrong type '%s' should be str" % type(value)
+ raise TypeError("wrong type '%s' should be str" % type(value))
(ip, port) = value.split(':')
ip = toIpAddress(ip)
if not 0 <= int(port) <= 0xffff:
- raise ValueError, 'invalid port %s' % port
+ raise ValueError('invalid port %s' % port)
return (ip, int(port))
def toVoltage(value):
class Grammar(object):
def setupLexerFactory(self, **kwargs):
if 'module' in kwargs:
- raise AttributeError, "module is an illegal attribute"
+ raise AttributeError("module is an illegal attribute")
self.lex_kwargs = kwargs
def setupParserFactory(self, **kwargs):
if 'module' in kwargs:
- raise AttributeError, "module is an illegal attribute"
+ raise AttributeError("module is an illegal attribute")
if 'output' in kwargs:
dir,tab = os.path.split(output)
if not tab.endswith('.py'):
- raise AttributeError, \
- 'The output file must end with .py'
+ raise AttributeError('The output file must end with .py')
kwargs['outputdir'] = dir
kwargs['tabmodule'] = tab[:-3]
return -1
return self.current_lexer.lineno
- raise AttributeError, \
- "'%s' object has no attribute '%s'" % (type(self), attr)
+ raise AttributeError(
+ "'%s' object has no attribute '%s'" % (type(self), attr))
def parse_string(self, data, source='<string>', debug=None, tracking=0):
if not isinstance(data, basestring):
- raise AttributeError, \
- "argument must be a string, was '%s'" % type(f)
+ raise AttributeError(
+ "argument must be a string, was '%s'" % type(f))
import new
lexer = self.lex.clone()
elif isinstance(f, file):
source = f.name
else:
- raise AttributeError, \
- "argument must be either a string or file, was '%s'" % type(f)
+ raise AttributeError(
+ "argument must be either a string or file, was '%s'" % type(f))
return self.parse_string(f.read(), source, **kwargs)
def update(self, obj):
if not isinstance(obj, Data):
- raise AttributeError, "can only update from Data object"
+ raise AttributeError("can only update from Data object")
for key,val in obj.__dict__.iteritems():
if key.startswith('_') or key in ('name', 'desc'):
if self.__dict__[key] == val:
continue
- raise AttributeError, \
- "%s specified more than once old: %s new: %s" % \
- (key, self.__dict__[key], val)
+ raise AttributeError(
+ "%s specified more than once old: %s new: %s" % \
+ (key, self.__dict__[key], val))
d = self.__dict__[key]
for k,v in val.iteritems():
if k in d:
- raise AttributeError, \
- "%s specified more than once in %s" % (k, key)
+ raise AttributeError(
+ "%s specified more than once in %s" % (k, key))
d[k] = v
if hasattr(self, 'system') and hasattr(obj, 'system'):
if self.system != obj.system:
- raise AttributeError, \
- "conflicting values for system: '%s'/'%s'" % \
- (self.system, obj.system)
+ raise AttributeError(
+ "conflicting values for system: '%s'/'%s'" % \
+ (self.system, obj.system))
def printinfo(self):
if self.name:
def __getitem__(self, key):
if key.startswith('_'):
- raise KeyError, "Key '%s' not found" % attr
+ raise KeyError("Key '%s' not found" % attr)
return self.__dict__[key]
def __iter__(self):
config = options[0]._config
for opt in options:
if opt._config != config:
- raise AttributeError, \
- "All options are not from the same Configuration"
+ raise AttributeError(
+ "All options are not from the same Configuration")
self._config = config
self._groups = [ opt._group for opt in options ]
def checkchildren(self, kids):
for kid in kids:
if kid._config != self:
- raise AttributeError, "child from the wrong configuration"
+ raise AttributeError("child from the wrong configuration")
def sortgroups(self, groups):
groups = [ (grp._number, grp) for grp in groups ]
if job.name == jobname:
return job
else:
- raise AttributeError, "job '%s' not found" % jobname
+ raise AttributeError("job '%s' not found" % jobname)
def job(self, options):
self.checkchildren(options)
filename = testname
break
else:
- raise AttributeError, \
- "Could not find file '%s'" % jobfile
+ raise AttributeError("Could not find file '%s'" % jobfile)
data = {}
execfile(filename, data)
if 'conf' not in data:
- raise ImportError, 'cannot import name conf from %s' % jobfile
+ raise ImportError('cannot import name conf from %s' % jobfile)
return data['conf']
def main(conf=None):
if conf is None:
if len(args) != 1:
- raise AttributeError, usage
+ raise AttributeError(usage)
conf = JobFile(args[0])
else:
if len(args) != 0:
- raise AttributeError, usage
+ raise AttributeError(usage)
if both:
jobs = conf.alljobs()
def __delitem__(self, key):
try:
del self.local[key]
- except KeyError, e:
+ except KeyError as e:
if key in self.parent:
self.deleted[key] = True
else:
- raise KeyError, e
+ raise KeyError(e)
def __setitem__(self, key, value):
self.deleted.pop(key, False)
def __getitem__(self, key):
try:
return self.local[key]
- except KeyError, e:
+ except KeyError as e:
if not self.deleted.get(key, False) and key in self.parent:
return self.parent[key]
else:
- raise KeyError, e
+ raise KeyError(e)
def __len__(self):
return len(self.local) + len(self.parent)
def get(self, key, default=None):
try:
return self[key]
- except KeyError, e:
+ except KeyError as e:
return default
def setdefault(self, key, default):