From fa21127a646b8d2a61fe412728762250ca38ecd2 Mon Sep 17 00:00:00 2001 From: Andreas Sandberg Date: Fri, 25 Jan 2019 11:32:25 +0000 Subject: python: Make exception handling Python 3 safe Change-Id: I9c2cdfad20deb1ddfa224320cf93f2105d126652 Reviewed-on: https://gem5-review.googlesource.com/c/15980 Maintainer: Andreas Sandberg Reviewed-by: Giacomo Travaglini --- src/python/importer.py | 2 +- src/python/m5/SimObject.py | 52 ++++++++-------- src/python/m5/main.py | 2 +- src/python/m5/params.py | 115 +++++++++++++++++------------------ src/python/m5/proxy.py | 26 ++++---- src/python/m5/simulate.py | 42 ++++++------- src/python/m5/ticks.py | 10 +-- src/python/m5/util/__init__.py | 6 +- src/python/m5/util/code_formatter.py | 2 +- src/python/m5/util/convert.py | 36 +++++------ src/python/m5/util/grammar.py | 19 +++--- src/python/m5/util/jobfile.py | 37 ++++++----- src/python/m5/util/multidict.py | 10 +-- 13 files changed, 177 insertions(+), 182 deletions(-) (limited to 'src') diff --git a/src/python/importer.py b/src/python/importer.py index fa26080e5..60b9b35cd 100644 --- a/src/python/importer.py +++ b/src/python/importer.py @@ -35,7 +35,7 @@ class CodeImporter(object): 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) diff --git a/src/python/m5/SimObject.py b/src/python/m5/SimObject.py index 44f26ea9b..97cf6d096 100644 --- a/src/python/m5/SimObject.py +++ b/src/python/m5/SimObject.py @@ -483,8 +483,8 @@ class MetaSimObject(type): 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] @@ -543,8 +543,8 @@ class MetaSimObject(type): 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) @@ -562,7 +562,7 @@ class MetaSimObject(type): 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, ) @@ -622,10 +622,10 @@ class MetaSimObject(type): 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) @@ -639,8 +639,8 @@ class MetaSimObject(type): 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': @@ -658,8 +658,8 @@ class MetaSimObject(type): 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__ @@ -1152,9 +1152,9 @@ class SimObject(object): # 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 @@ -1196,7 +1196,7 @@ class SimObject(object): 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). @@ -1216,7 +1216,7 @@ class SimObject(object): 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, ) @@ -1240,8 +1240,8 @@ class SimObject(object): 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 @@ -1249,7 +1249,7 @@ class SimObject(object): 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 @@ -1352,18 +1352,18 @@ class SimObject(object): 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 @@ -1533,7 +1533,7 @@ class SimObject(object): 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 @@ -1541,8 +1541,8 @@ class SimObject(object): 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): @@ -1650,7 +1650,7 @@ def tryAsSimObjectOrVector(value): 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() diff --git a/src/python/m5/main.py b/src/python/m5/main.py index 9d46d4331..d8c0d923b 100644 --- a/src/python/m5/main.py +++ b/src/python/m5/main.py @@ -209,7 +209,7 @@ def main(*args): 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 diff --git a/src/python/m5/params.py b/src/python/m5/params.py index 854c8e379..0a563b8f2 100644 --- a/src/python/m5/params.py +++ b/src/python/m5/params.py @@ -155,7 +155,7 @@ class ParamDesc(object): 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')) @@ -168,10 +168,10 @@ class ParamDesc(object): 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': @@ -180,8 +180,8 @@ class ParamDesc(object): 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"): @@ -234,8 +234,8 @@ class ParamDesc(object): 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] @@ -539,8 +539,8 @@ class CheckedInt(NumericParamValue): 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): @@ -548,8 +548,8 @@ class CheckedInt(NumericParamValue): 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): @@ -614,8 +614,8 @@ class Float(ParamValue, float): 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) @@ -711,7 +711,7 @@ class AddrRange(ParamValue): 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: @@ -742,10 +742,10 @@ class AddrRange(ParamValue): 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' \ @@ -885,15 +885,15 @@ class EthernetAddr(ParamValue): 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 @@ -966,7 +966,7 @@ class IpAddress(ParamValue): 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 @@ -991,7 +991,7 @@ class IpNetmask(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') @@ -1000,7 +1000,7 @@ class IpNetmask(IpAddress): 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): @@ -1013,10 +1013,10 @@ class IpNetmask(IpAddress): 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() @@ -1041,7 +1041,7 @@ class IpNetmask(IpAddress): 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 @@ -1065,7 +1065,7 @@ class IpWithPort(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') @@ -1074,7 +1074,7 @@ class IpWithPort(IpAddress): 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): @@ -1087,10 +1087,10 @@ class IpWithPort(IpAddress): 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() @@ -1115,7 +1115,7 @@ class IpWithPort(IpAddress): 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 @@ -1157,7 +1157,7 @@ def parse_time(value): 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' @@ -1226,22 +1226,22 @@ class MetaEnum(MetaParamValue): 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 @@ -1385,8 +1385,8 @@ class Enum(ParamValue): 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): @@ -1491,7 +1491,7 @@ class Latency(TickParamValue): 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: @@ -1533,7 +1533,7 @@ class Frequency(TickParamValue): 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): @@ -1578,7 +1578,7 @@ class Clock(TickParamValue): 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() @@ -1800,8 +1800,8 @@ class PortRef(object): 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., @@ -1821,9 +1821,8 @@ class PortRef(object): 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 @@ -1836,9 +1835,9 @@ class PortRef(object): 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': @@ -1892,9 +1891,9 @@ class PortRef(object): # 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 @@ -1951,7 +1950,7 @@ class VectorPortRef(object): 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) @@ -1964,7 +1963,7 @@ class VectorPortRef(object): 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): @@ -2029,7 +2028,7 @@ class MasterPort(Port): 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") @@ -2038,7 +2037,7 @@ class SlavePort(Port): 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). @@ -2057,7 +2056,7 @@ class VectorMasterPort(VectorPort): 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") @@ -2067,7 +2066,7 @@ class VectorSlavePort(VectorPort): 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 diff --git a/src/python/m5/proxy.py b/src/python/m5/proxy.py index c0bf84a93..2a3250020 100644 --- a/src/python/m5/proxy.py +++ b/src/python/m5/proxy.py @@ -66,16 +66,16 @@ class BaseProxy(object): 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 @@ -88,8 +88,8 @@ class BaseProxy(object): # 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 @@ -116,13 +116,13 @@ class BaseProxy(object): 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) @@ -157,7 +157,7 @@ class AttrProxy(BaseProxy): 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 @@ -168,9 +168,9 @@ class AttrProxy(BaseProxy): # 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 diff --git a/src/python/m5/simulate.py b/src/python/m5/simulate.py index 0e1a67e47..03cc253e9 100644 --- a/src/python/m5/simulate.py +++ b/src/python/m5/simulate.py @@ -221,7 +221,7 @@ def memInvalidate(root): 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) @@ -230,8 +230,8 @@ def checkpoint(dir): 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: @@ -253,10 +253,10 @@ def switchCpus(system, cpuList, verbose=True): 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] @@ -264,33 +264,31 @@ def switchCpus(system, cpuList, verbose=True): 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() @@ -343,13 +341,13 @@ def fork(simout="%(parent)s.f%(fork_seq)i"): 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: diff --git a/src/python/m5/ticks.py b/src/python/m5/ticks.py index e4b5eac7e..22a5738d3 100644 --- a/src/python/m5/ticks.py +++ b/src/python/m5/ticks.py @@ -47,8 +47,8 @@ def setGlobalFrequency(ticksPerSecond): 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? @@ -58,13 +58,13 @@ def fromSeconds(value): 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 diff --git a/src/python/m5/util/__init__.py b/src/python/m5/util/__init__.py index 2ad9c5627..02dece69b 100644 --- a/src/python/m5/util/__init__.py +++ b/src/python/m5/util/__init__.py @@ -128,7 +128,7 @@ def compareVersions(v1, v2): 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) @@ -194,7 +194,7 @@ def readCommand(cmd, **kwargs): kwargs.setdefault('close_fds', True) try: subp = Popen(cmd, **kwargs) - except Exception, e: + except Exception as e: if no_exception: return exception raise @@ -206,7 +206,7 @@ def makeDir(path): 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) diff --git a/src/python/m5/util/code_formatter.py b/src/python/m5/util/code_formatter.py index a11c9d3d0..d48c59b26 100644 --- a/src/python/m5/util/code_formatter.py +++ b/src/python/m5/util/code_formatter.py @@ -74,7 +74,7 @@ class lookup(object): 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""" diff --git a/src/python/m5/util/convert.py b/src/python/m5/util/convert.py index 5ae31216b..7b9cb3812 100644 --- a/src/python/m5/util/convert.py +++ b/src/python/m5/util/convert.py @@ -89,7 +89,7 @@ binary_prefixes = { 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 @@ -102,8 +102,8 @@ def toFloat(value, target_type='float', units=None, prefixes=[]): 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)] @@ -124,8 +124,8 @@ def toInteger(value, target_type='integer', units=None, prefixes=[]): 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 @@ -155,7 +155,7 @@ def anyToLatency(value): """result is a clock period""" try: return 1 / toFrequency(value) - except ValueError, ZeroDivisionError: + except (ValueError, ZeroDivisionError): pass try: @@ -163,7 +163,7 @@ def anyToLatency(value): 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""" @@ -174,10 +174,10 @@ def anyToFrequency(value): 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') @@ -190,29 +190,29 @@ def toMemorySize(value): 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) @@ -223,18 +223,18 @@ def toIpNetmask(value): 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): diff --git a/src/python/m5/util/grammar.py b/src/python/m5/util/grammar.py index 07702cfad..bb3429866 100644 --- a/src/python/m5/util/grammar.py +++ b/src/python/m5/util/grammar.py @@ -37,18 +37,17 @@ class ParseError(Exception): 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] @@ -90,13 +89,13 @@ class Grammar(object): 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='', 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() @@ -120,8 +119,8 @@ class Grammar(object): 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) diff --git a/src/python/m5/util/jobfile.py b/src/python/m5/util/jobfile.py index d8c09afd4..ad5b5ff5c 100644 --- a/src/python/m5/util/jobfile.py +++ b/src/python/m5/util/jobfile.py @@ -38,7 +38,7 @@ class Data(object): 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'): @@ -52,22 +52,22 @@ class Data(object): 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: @@ -96,7 +96,7 @@ class Data(object): 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): @@ -131,8 +131,8 @@ class Job(Data): 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 ] @@ -309,7 +309,7 @@ class Configuration(Data): 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 ] @@ -387,7 +387,7 @@ class Configuration(Data): 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) @@ -414,13 +414,12 @@ def JobFile(jobfile): 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): @@ -448,11 +447,11 @@ 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() diff --git a/src/python/m5/util/multidict.py b/src/python/m5/util/multidict.py index d22b1cbbc..28090a251 100644 --- a/src/python/m5/util/multidict.py +++ b/src/python/m5/util/multidict.py @@ -48,11 +48,11 @@ class multidict(object): 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) @@ -61,11 +61,11 @@ class multidict(object): 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) @@ -106,7 +106,7 @@ class multidict(object): def get(self, key, default=None): try: return self[key] - except KeyError, e: + except KeyError as e: return default def setdefault(self, key, default): -- cgit v1.2.3