From ed41e18c95e5e61f7968558afad337f6225e4766 Mon Sep 17 00:00:00 2001 From: cloud Date: Wed, 18 Aug 2021 22:09:28 +0200 Subject: [PATCH] Fix: python exceptions, pep, and fixed bytes_list --- python/MDSplus/__init__.py | 16 +- python/MDSplus/_mdsshr.py | 2 +- python/MDSplus/apd.py | 4 +- python/MDSplus/compound.py.in | 498 ++++++++++++++++++++-------------- python/MDSplus/connection.py | 10 +- python/MDSplus/descriptor.py | 57 ++-- python/MDSplus/event.py | 30 +- python/MDSplus/magic.py | 46 ++-- python/MDSplus/mdsarray.py | 49 ++-- python/MDSplus/mdsdata.py | 19 +- python/MDSplus/mdsdcl.py | 15 +- python/MDSplus/mdsscalar.py | 54 ++-- python/MDSplus/modpython.py | 20 +- python/MDSplus/scope.py | 2 +- python/MDSplus/tree.py | 67 +++-- python/MDSplus/version.py | 15 +- python/MDSplus/wsgi/doPlot.py | 2 +- 17 files changed, 497 insertions(+), 409 deletions(-) diff --git a/python/MDSplus/__init__.py b/python/MDSplus/__init__.py index 3d6f2f5cfb..3e78956f9b 100644 --- a/python/MDSplus/__init__.py +++ b/python/MDSplus/__init__.py @@ -42,7 +42,7 @@ def _mimport(name, level=1): if not __package__: return __import__(name, globals()) return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) @@ -67,11 +67,11 @@ class libs: TdiShr = _ver.load_library('TdiShr') try: Mdsdcl = _ver.load_library('Mdsdcl') - except: + except Exception: Mdsdcl = None try: MdsIpShr = _ver.load_library('MdsIpShr') - except: + except Exception: MdsIpShr = None @@ -89,7 +89,7 @@ class libs: Version: %s Release Date: %s """ % (__doc__, __version__, _version.release_date) -except: +except Exception: if version_check and 'PYTHONPATH' in os.environ: sys.stderr.write( "PYTHONPATH was set to: %s and unable to import version information\n" % os.environ['PYTHONPATH']) @@ -100,7 +100,7 @@ def version_check(): try: libs.MdsShr.MdsRelease.restype = ctypes.c_char_p verchk = _ver.tostr(libs.MdsShr.MdsRelease()) - except: + except Exception: verchk = "unknown" if verchk != __version__ or verchk == "unknown": sys.stderr.write('''Warning: @@ -113,7 +113,7 @@ def version_check(): del version_check -def load_package(gbls={}, version_check=False): +def load_package(gbls, version_check=False): def loadmod_full(name, gbls): mod = _mimport(name) for key in mod.__dict__: @@ -146,7 +146,7 @@ def PyLib(): else 'python%d.%d') % sys.version_info[0:2] try: lib = ctypes.util.find_library(name) - except: + except Exception: lib = None if lib is None: lib = os.getenv("PyLib", None) @@ -159,7 +159,7 @@ def PyLib(): load_package(globals(), True) try: _mimport("magic") # load ipython magic - except: + except Exception: pass del load_package del _ver diff --git a/python/MDSplus/_mdsshr.py b/python/MDSplus/_mdsshr.py index b52c2bde2a..23e5274d43 100644 --- a/python/MDSplus/_mdsshr.py +++ b/python/MDSplus/_mdsshr.py @@ -30,7 +30,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) diff --git a/python/MDSplus/apd.py b/python/MDSplus/apd.py index f9066a2c6b..e6c4f48fe2 100644 --- a/python/MDSplus/apd.py +++ b/python/MDSplus/apd.py @@ -27,7 +27,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) @@ -52,7 +52,7 @@ class Apd(_dat.TreeRefX, _arr.Array): @property def _descriptor(self): descs = self.descs - d = _dsc.Descriptor_apd() + d = _dsc.DescriptorAPD() d.scale = 0 d.digits = 0 d.aflags = 0 diff --git a/python/MDSplus/compound.py.in b/python/MDSplus/compound.py.in index e5fa2b3d42..3dadbda676 100644 --- a/python/MDSplus/compound.py.in +++ b/python/MDSplus/compound.py.in @@ -23,51 +23,56 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # +import ctypes as _C +import numpy as _N + + def _mimport(name, level=1): try: return __import__(name, globals(), level=level) except: return __import__(name, globals()) -import ctypes as _C -import numpy as _N -_ver=_mimport('version') -_dsc=_mimport('descriptor') -_dat=_mimport('mdsdata') -_tre=_mimport('tree') -_exc=_mimport('mdsExceptions') +_ver = _mimport('version') +_dsc = _mimport('descriptor') +_dat = _mimport('mdsdata') +_tre = _mimport('tree') +_exc = _mimport('mdsExceptions') + class Compound(_dat.DataX): maxdesc = 255 fields = tuple() + def __dir__(self): """used for tab completion""" - return list(self.fields)+_ver.superdir(Compound,self) + return list(self.fields)+_ver.superdir(Compound, self) - def __init__(self,*args, **kwargs): + def __init__(self, *args, **kwargs): """MDSplus compound data.""" - if len(args)==1 and args[0] is self: return + if len(args) == 1 and args[0] is self: + return if self.__class__ is Compound: raise TypeError("Cannot create instances of class Compound") - self._fields={} + self._fields = {} for idx in range(len(self.fields)): - self._fields[self.fields[idx]]=idx - self._argOffset=len(self.fields) + self._fields[self.fields[idx]] = idx + self._argOffset = len(self.fields) self.setDescs(args) - for k,v in kwargs: + for k, v in kwargs: if k in self.fields: - self.setDescAt(self._fields[k],v) + self.setDescAt(self._fields[k], v) @property def deref(self): for i in range(self.getNumDescs()): ans = self.getDescAt(i) - if isinstance(ans,(_dat.Data,_tre.TreeNode)): - self.setDescAt(i,ans.deref) + if isinstance(ans, (_dat.Data, _tre.TreeNode)): + self.setDescAt(i, ans.deref) return self - def __getattr__(self,name): + def __getattr__(self, name): if name == '_fields': return {} if name in self._fields: @@ -78,18 +83,17 @@ class Compound(_dat.DataX): return getter elif name.startswith('set') and name[3:].lower() in self._fields: def setter(value): - self.__setattr__(name[3:].lower(),value) + self.__setattr__(name[3:].lower(), value) return setter - return super(Compound,self).__getattr__(name) - #raise AttributeError("No such attribute '%s' in %s"%(name,self.__class__.__name__)) + return super(Compound, self).__getattr__(name) - def __setattr__(self,name,value): + def __setattr__(self, name, value): if name in self._fields: - self.setDescAt(self._fields[name],value) + self.setDescAt(self._fields[name], value) else: - super(Compound,self).__setattr__(name,value) + super(Compound, self).__setattr__(name, value) - def getArgumentAt(self,idx): + def getArgumentAt(self, idx): """Return argument at index idx (indexes start at 0) @rtype: Data,None """ @@ -99,65 +103,68 @@ class Compound(_dat.DataX): """Return arguments @rtype: Data,None """ - return self.getDescAt(slice(self._argOffset,None)) + return self.getDescAt(slice(self._argOffset, None)) - def setArgumentAt(self,idx,value): + def setArgumentAt(self, idx, value): """Set argument at index idx (indexes start at 0)""" return self.setDescAt(self._argOffset+idx, value) - def setArguments(self,args): + def setArguments(self, args): """Set arguments @type args: tuple """ self._descs = self._descs[:self._argOffset+len(args)] - return self.setDescAt(slice(self._argOffset,None),args) + return self.setDescAt(slice(self._argOffset, None), args) def removeTail(self): - """ removes tailing None args """ - if len(self._descs) <= self._argOffset: return - for last in range(len(self._descs)-1,self._argOffset-1,-1): - if self._descs[last] is not None: break - if last < len(self._descs): - self._descs = self._descs[:last+1] - - def setDescs(self,args): + """ removes tailing None args """ + if len(self._descs) <= self._argOffset: + return + for last in range(len(self._descs)-1, self._argOffset-1, -1): + if self._descs[last] is not None: + break + if last < len(self._descs): + self._descs = self._descs[:last+1] + + def setDescs(self, args): """Set descriptors @type args: tuple """ self._descs = [_dat.Data(arg) for arg in args] self._setTree(*args) - while self.getNumDescs()0: + def fromDescriptor(cls, d): + args = [_dsc.pointerToObject(d.dscptrs[i], d.tree) + for i in _ver.xrange(d.ndesc)] + ans = cls(*args) + if d.length > 0: if d.length == 1: - opcptr=_C.cast(d.pointer,_C.POINTER(_C.c_uint8)) + opcptr = _C.cast(d.pointer, _C.POINTER(_C.c_uint8)) elif d.length == 2: - opcptr=_C.cast(d.pointer,_C.POINTER(_C.c_uint16)) + opcptr = _C.cast(d.pointer, _C.POINTER(_C.c_uint16)) else: - opcptr=_C.cast(d.pointer,_C.POINTER(_C.c_uint32)) + opcptr = _C.cast(d.pointer, _C.POINTER(_C.c_uint32)) ans.opcode = opcptr.contents.value return ans._setTree(d.tree) -class Action(_dat.TreeRefX,Compound): + +class Action(_dat.TreeRefX, Compound): """ An Action is used for describing an operation to be performed by an MDSplus action server. Actions are typically dispatched using the mdstcl DISPATCH command """ - fields=('dispatch','task','errorLog','completionMessage','performance') - dtype_id=202 -_dsc.addDtypeToClass(Action) + fields = ('dispatch', 'task', 'errorLog', + 'completionMessage', 'performance') + dtype_id = 202 + -class Call(_dat.TreeRef,Compound): +_dsc._add_dtype_to_class(Action) + + +class Call(_dat.TreeRef, Compound): """ A Call is used to call routines in shared libraries. """ - fields=('image','routine') - dtype_id=212 - def setRType(self,data): - if isinstance(data,_dat.Data) or (isinstance(data,type) and issubclass(data,_dat.Data)): - self.opcode=data.dtype_id + fields = ('image', 'routine') + dtype_id = 212 + + def setRType(self, data): + if isinstance(data, _dat.Data) or (isinstance(data, type) and issubclass(data, _dat.Data)): + self.opcode = data.dtype_id else: self.opcode = int(data) return self -_dsc.addDtypeToClass(Call) -class Conglom(_dat.TreeRefX,Compound): + +_dsc._add_dtype_to_class(Call) + + +class Conglom(_dat.TreeRefX, Compound): """A Conglom is used at the head of an MDSplus conglomerate. A conglomerate is a set of tree nodes used to define a device such as a piece of data acquisition hardware. A conglomerate is associated with some external code providing various methods which can be performed on the device. The Conglom class contains information used for locating the external code. """ - fields=('image','model','name','qualifiers') - dtype_id=200 + fields = ('image', 'model', 'name', 'qualifiers') + dtype_id = 200 @property def __model_unique(self): model = str(self.model) hashval = self.name.data() if hashval is None: - return model,None - return model, '%s_%016x'%(model,hashval) + return model, None + return model, '%s_%016x' % (model, hashval) - def getDevice(self,*args,**kwargs): - if not self.image=='__python__': + def getDevice(self, *args, **kwargs): + if not self.image == '__python__': raise _exc.DevNOT_A_PYDEVICE - import imp,sys - model,unique = self.__model_unique + import imp + import sys + model, unique = self.__model_unique if unique is None: module = imp.new_module(model) qualifiers = self.qualifiers.data() - if isinstance(qualifiers,_ver.basestring): + if isinstance(qualifiers, _ver.basestring): try: if qualifiers.startswith("Device.PyDevice("): - module.__dict__[model] = eval(compile(qualifiers,model,'eval'),{'Device':_tre.Device},module.__dict__) - else: exec(compile(qualifiers,model,'exec'),{},module.__dict__) - except: pass + module.__dict__[model] = eval(compile(qualifiers, model, 'eval'), { + 'Device': _tre.Device}, module.__dict__) + else: + exec(compile(qualifiers, model, 'exec'), + {}, module.__dict__) + except: + pass else: if unique in sys.modules: module = sys.modules[unique] else: module = imp.new_module(unique) qualifiers = self.qualifiers.data() - if isinstance(qualifiers,_N.ndarray) and qualifiers.dtype == _N.uint8: + if isinstance(qualifiers, _N.ndarray) and qualifiers.dtype == _N.uint8: qualifiers = qualifiers.tostring() - elif isinstance(qualifiers,_N.generic): + elif isinstance(qualifiers, _N.generic): qualifiers = qualifiers.tolist() - if isinstance(qualifiers,list): - qualifiers = '\n'.join(qualifiers) # treat as line-by-line - try: exec(compile(qualifiers,model,'exec'),module.__dict__,module.__dict__) - except: pass - else: sys.modules[unique] = module + if isinstance(qualifiers, list): + # treat as line-by-line + qualifiers = '\n'.join(qualifiers) + try: + exec(compile(qualifiers, model, 'exec'), + module.__dict__, module.__dict__) + except: + pass + else: + sys.modules[unique] = module if model in module.__dict__: cls = module.__dict__[model] else: cls = _tre.Device.PyDevice(model) - if issubclass(cls,(_tre.Device,)): - return cls if len(args)+len(kwargs)==0 else cls(*args,**kwargs) + if issubclass(cls, (_tre.Device,)): + return cls if len(args)+len(kwargs) == 0 else cls(*args, **kwargs) raise _exc.DevPYDEVICE_NOT_FOUND -_dsc.addDtypeToClass(Conglom) -class Dependency(_dat.TreeRefX,Compound): + +_dsc._add_dtype_to_class(Conglom) + + +class Dependency(_dat.TreeRefX, Compound): """A Dependency object is used to describe action dependencies. This is a legacy class and may not be recognized by some dispatching systems """ - fields=('arg1','arg2') - dtype_id=208 -_dsc.addDtypeToClass(Dependency) + fields = ('arg1', 'arg2') + dtype_id = 208 + + +_dsc._add_dtype_to_class(Dependency) + -class Dimension(_dat.TreeRefX,Compound): +class Dimension(_dat.TreeRefX, Compound): """A dimension object is used to describe a signal dimension, typically a time axis. It provides a compact description of the timing information of measurements recorded by devices such as transient recorders. It associates a Window object with an axis. The axis is generally a range with possibly no start or end but simply a delta. The Window object is then used to bracket the axis to resolve the appropriate timestamps. """ - fields=('window','axis') - dtype_id=196 -_dsc.addDtypeToClass(Dimension) + fields = ('window', 'axis') + dtype_id = 196 -class Dispatch(_dat.TreeRefX,Compound): + +_dsc._add_dtype_to_class(Dimension) + + +class Dispatch(_dat.TreeRefX, Compound): """A Dispatch object is used to describe when an where an action should be dispatched to an MDSplus action server. """ - fields=('ident','phase','when','completion') - dtype_id=203 + fields = ('ident', 'phase', 'when', 'completion') + dtype_id = 203 - def __init__(self,*args,**kwargs): - if len(args)==1 and args[0] is self: return + def __init__(self, *args, **kwargs): + if len(args) == 1 and args[0] is self: + return if 'type' in kwargs: - self.opcode=kwargs['type'] + self.opcode = kwargs['type'] else: - self.opcode=2 - super(Dispatch,self).__init__(*args,**kwargs) -_dsc.addDtypeToClass(Dispatch) + self.opcode = 2 + super(Dispatch, self).__init__(*args, **kwargs) + + +_dsc._add_dtype_to_class(Dispatch) + +_TdiShr = _ver.load_library('TdiShr') -_TdiShr=_ver.load_library('TdiShr') class Function(Compound): """A Function object is used to reference builtin MDSplus functions. For example the expression 1+2 is represented in as Function instance created by Function(opcode='ADD',args=(1,2)) """ - fields=tuple() - dtype_id=199 - opcodeToClass={} + fields = tuple() + dtype_id = 199 + opcodeToClass = {} @classmethod - def fromDescriptor(cls,d): - opc = _C.cast(d.pointer,_C.POINTER(_C.c_uint16)).contents.value - args = [_dsc.pointerToObject(d.dscptrs[i],d.tree) for i in _ver.xrange(d.ndesc)] + def fromDescriptor(cls, d): + opc = _C.cast(d.pointer, _C.POINTER(_C.c_uint16)).contents.value + args = [_dsc.pointerToObject(d.dscptrs[i], d.tree) + for i in _ver.xrange(d.ndesc)] return cls.opcodeToClass[opc](*args) - def __init__(self,*args): + def __init__(self, *args): """Create a compiled MDSplus function reference. Number of arguments allowed depends on the opcode supplied. """ - if len(args)==1 and args[0] is self: return - if len(args)>self.max_args or (self.max_args>0 and len(args) self.max_args or (self.max_args > 0 and len(args) < self.min_args): + if self.max_args == 0 or self.max_args == self.min_args: + raise TypeError("Requires %d input arguments for %s but %d given" % ( + self.max_args, self.__class__.__name__, len(args))) else: - raise TypeError("Requires %d to %d input arguments for %s but %d given"%(self.min_args,self.max_args,self.__class__.__name__,len(args))) - super(Function,self).__init__(*args) + raise TypeError("Requires %d to %d input arguments for %s but %d given" % ( + self.min_args, self.max_args, self.__class__.__name__, len(args))) + super(Function, self).__init__(*args) + @classmethod def name(cls): if cls.__name__.startswith('d'): - return '$%s'%cls.__name__[1:] + return '$%s' % cls.__name__[1:] return cls.__name__ def evaluate(self): @@ -338,92 +383,116 @@ class Function(Compound): nargs = len(dargs) argslist = (_C.c_void_p*nargs)() for i in _ver.xrange(nargs): - argslist[i] = _C.cast(_dat.Data.pointer(dargs[i]),_C.c_void_p) - xd = _dsc.Descriptor_xd() - if isinstance(self,_dat.TreeRef): + argslist[i] = _C.cast(_dat.Data.pointer(dargs[i]), _C.c_void_p) + xd = _dsc.DescriptorXD() + if isinstance(self, _dat.TreeRef): tree = self.tree - if isinstance(tree,_tre.Tree): - _exc.checkStatus(_TdiShr._TdiIntrinsic(tree.pctx,self.opcode,nargs,argslist,xd.ref)) + if isinstance(tree, _tre.Tree): + _exc.checkStatus(_TdiShr._TdiIntrinsic( + tree.pctx, self.opcode, nargs, argslist, xd.ref)) return xd._setTree(tree).value - _exc.checkStatus(_TdiShr. TdiIntrinsic( self.opcode,nargs,argslist,xd.ref)) + _exc.checkStatus(_TdiShr. TdiIntrinsic( + self.opcode, nargs, argslist, xd.ref)) return xd.value -_dsc.addDtypeToClass(Function) -class Method(_dat.TreeRefX,Compound): + +_dsc._add_dtype_to_class(Function) + + +class Method(_dat.TreeRefX, Compound): """A Method object is used to describe an operation to be performed on an MDSplus conglomerate/device """ - fields=('timeout','method','object') - dtype_id=207 -_dsc.addDtypeToClass(Method) + fields = ('timeout', 'method', 'object') + dtype_id = 207 + + +_dsc._add_dtype_to_class(Method) + -class Procedure(_dat.TreeRef,Compound): +class Procedure(_dat.TreeRef, Compound): """A Procedure is a deprecated object """ - fields=('timeout','language','procedure') - dtype_id=206 -_dsc.addDtypeToClass(Procedure) + fields = ('timeout', 'language', 'procedure') + dtype_id = 206 -class Program(_dat.TreeRef,Compound): + +_dsc._add_dtype_to_class(Procedure) + + +class Program(_dat.TreeRef, Compound): """A Program is a deprecated object""" - fields=('timeout','program') - dtype_id=204 -_dsc.addDtypeToClass(Program) + fields = ('timeout', 'program') + dtype_id = 204 + + +_dsc._add_dtype_to_class(Program) -class Range(_dat.TreeRefX,Compound): + +class Range(_dat.TreeRefX, Compound): """A Range describes a ramp. When used as an axis in a Dimension object along with a Window object it can be used to describe a clock. In this context it is possible to have missing begin and ending values or even have the begin, ending, and delta fields specified as arrays to indicate a multi-speed clock. """ - fields=('begin','ending','delta') - dtype_id=201 + fields = ('begin', 'ending', 'delta') + dtype_id = 201 @property def slice(self): - return slice(self.begin.data(),self.ending.data(),self.delta.data()) -_dsc.addDtypeToClass(Range) + return slice(self.begin.data(), self.ending.data(), self.delta.data()) + + +_dsc._add_dtype_to_class(Range) -class Routine(_dat.TreeRef,Compound): + +class Routine(_dat.TreeRef, Compound): """A Routine is a deprecated object""" - fields=('timeout','image','routine') - dtype_id=205 -_dsc.addDtypeToClass(Routine) + fields = ('timeout', 'image', 'routine') + dtype_id = 205 + -class Slope(_dat.TreeRefX,Compound): +_dsc._add_dtype_to_class(Routine) + + +class Slope(_dat.TreeRefX, Compound): """A Slope is a deprecated object. You should use Range instead.""" - fields=('slope','begin','end') - dtype_id=198 + fields = ('slope', 'begin', 'end') + dtype_id = 198 + def slice(self): - return slice(self.begin.data(),self.end.data(),self.slope.data()) -_dsc.addDtypeToClass(Slope) + return slice(self.begin.data(), self.end.data(), self.slope.data()) + + +_dsc._add_dtype_to_class(Slope) -class Signal(_dat.TreeRefX,Compound): + +class Signal(_dat.TreeRefX, Compound): """A Signal is used to describe a measurement, usually time dependent, and associated the data with its independent axis (Dimensions). When Signals are indexed using s[idx], the index is resolved using the dimension of the signal """ - fields=('value','raw') - dtype_id=195 + fields = ('value', 'raw') + dtype_id = 195 @property def dims(self): """The dimensions of the signal""" return self.getArguments() - def dim_of(self,idx=0): + def dim_of(self, idx=0): """Return the signals dimension @rtype: Data """ return self.getDimensionAt(idx) - def __getitem__(self,idx): + def __getitem__(self, idx): """Subscripting <==> signal[subscript]. Uses the dimension information for subscripting @param idx: index or Range used for subscripting the signal based on the signals dimensions @type idx: Data @rtype: Signal """ - if isinstance(idx,slice): - idx = Range(idx.start,idx.stop,idx.step) - return _dat.Data.execute('$[$]',self,idx) + if isinstance(idx, slice): + idx = Range(idx.start, idx.stop, idx.step) + return _dat.Data.execute('$[$]', self, idx) - def getDimensionAt(self,idx=0): + def getDimensionAt(self, idx=0): """Return the dimension of the signal @param idx: The index of the desired dimension. Indexes start at 0. 0=default @type idx: int @@ -437,44 +506,50 @@ class Signal(_dat.TreeRefX,Compound): """ return self.getArguments() - def setDimensionAt(self,idx,value): + def setDimensionAt(self, idx, value): """Set the dimension @param idx: The index into the dimensions of the signal. @rtype: None """ - return self.setArgumentAt(idx,value) + return self.setArgumentAt(idx, value) - def setDimensions(self,value): + def setDimensions(self, value): """Set all the dimensions of a signal @param value: The dimensions @type value: tuple @rtype: None """ return self.setArguments(value) -_dsc.addDtypeToClass(Signal) -class Window(_dat.TreeRefX,Compound): + +_dsc._add_dtype_to_class(Signal) + + +class Window(_dat.TreeRefX, Compound): """A Window object can be used to construct a Dimension object. It brackets the axis information stored in the Dimension to construct the independent axis of a signal. """ - fields=('startIdx','endIdx','timeAt0') - dtype_id=197 -_dsc.addDtypeToClass(Window) + fields = ('startIdx', 'endIdx', 'timeAt0') + dtype_id = 197 -class Opaque(_dat.TreeRefX,Compound): + +_dsc._add_dtype_to_class(Window) + + +class Opaque(_dat.TreeRefX, Compound): """An Opaque object containing a binary uint8 array and a string identifying the type. """ - fields=('value','otype') - dtype_id=217 - + fields = ('value', 'otype') + dtype_id = 217 @property def value(self): "Data portion of Opaque object" return self.getDescAt(0) + @value.setter - def value(self,value): - self.setDescAt(0,value) + def value(self, value): + self.setDescAt(0, value) @property def image(self): @@ -482,8 +557,10 @@ class Opaque(_dat.TreeRefX,Compound): return self.getImage() def getImage(self): - try: from PIL import Image - except: import Image + try: + from PIL import Image + except: + import Image if _ver.ispy3: from io import BytesIO as io else: @@ -491,7 +568,7 @@ class Opaque(_dat.TreeRefX,Compound): return Image.open(io(self.value.data().tostring())) @classmethod - def fromFile(cls,filename,typestring=None): + def fromFile(cls, filename, typestring=None): """Read a file and return an Opaque object @param filename: Name of file to read in @type filename: str @@ -502,35 +579,48 @@ class Opaque(_dat.TreeRefX,Compound): import os if typestring is None: fn, typestring = os.path.splitext(filename) - f = open(filename,'rb') + f = open(filename, 'rb') try: - opq=cls(_dat.Data(_N.fromstring(f.read(),dtype="uint8")),typestring) + opq = cls(_dat.Data(_N.fromstring( + f.read(), dtype="uint8")), typestring) finally: f.close() return opq -_dsc.addDtypeToClass(Opaque) + + +_dsc._add_dtype_to_class(Opaque) + class WithCompound(Compound): def __str__(self): return str(self.__getattr__('data')) def __bytes__(self): return bytes(self.__getattr__('data')) -class WithUnits(_dat.TreeRefX,WithCompound): + +class WithUnits(_dat.TreeRefX, WithCompound): """Specifies a units for any kind of data. """ - fields=('data','units') - dtype_id=211 -_dsc.addDtypeToClass(WithUnits) + fields = ('data', 'units') + dtype_id = 211 + + +_dsc._add_dtype_to_class(WithUnits) -class WithError(_dat.TreeRefX,WithCompound): + +class WithError(_dat.TreeRefX, WithCompound): """Specifies error information for any kind of data. """ - fields=('data','error') - dtype_id=213 -_dsc.addDtypeToClass(WithError) + fields = ('data', 'error') + dtype_id = 213 + -class Parameter(_dat.TreeRefX,WithCompound): +_dsc._add_dtype_to_class(WithError) + + +class Parameter(_dat.TreeRefX, WithCompound): """Specifies a help text and validation information for any kind of data. """ - fields=('data','help','validation') - dtype_id=194 -_dsc.addDtypeToClass(Parameter) + fields = ('data', 'help', 'validation') + dtype_id = 194 + + +_dsc._add_dtype_to_class(Parameter) diff --git a/python/MDSplus/connection.py b/python/MDSplus/connection.py index 27e0c1ac48..deeec5e6ea 100644 --- a/python/MDSplus/connection.py +++ b/python/MDSplus/connection.py @@ -32,7 +32,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) @@ -63,6 +63,8 @@ class MdsIpException(_exc.MDSplusException): INVALID_CONNECTION_ID = -1 + + class _Connection: _conid = INVALID_CONNECTION_ID @@ -149,12 +151,12 @@ def _get_answer(self, to_msec=-1): elif dtype == 13: dtype = 55 if ndims.value == 0: - d = _dsc.Descriptor_s() + d = _dsc.DescriptorS() d.dtype = dtype d.length = length.value d.pointer = ans return d.value - val = _dsc.Descriptor_a() + val = _dsc.DescriptorA() val.dtype = dtype val.dclass = 4 val.length = length.value @@ -172,7 +174,7 @@ def _get_answer(self, to_msec=-1): return val.value except _exc.MDSplusException: if ndims.value == 0 and dtype == _sca.String.dtype_id: - d = _dsc.Descriptor_s() + d = _dsc.DescriptorS() d.dtype = dtype d.length = length.value d.pointer = ans diff --git a/python/MDSplus/descriptor.py b/python/MDSplus/descriptor.py index 1201090c34..055bf1a2d1 100644 --- a/python/MDSplus/descriptor.py +++ b/python/MDSplus/descriptor.py @@ -24,15 +24,16 @@ # +import ctypes as _C + + def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) -import ctypes as _C - _ver = _mimport('version') _exc = _mimport('mdsExceptions') @@ -115,7 +116,7 @@ def __new__(cls, obj_in=None, _dict_={}): def __init__(self, obj_in=None, _dict_={}): if self.__class__ is Descriptor: - return Exception("cannot instanciate Descriptor") + raise _exc.MdsException("cannot instanciate Descriptor") for k, v in _dict_.items(): if k not in ['ptr', 'ptr_']: self.__dict__[k] = v @@ -155,13 +156,13 @@ class DescriptorNULL(Descriptor): dclass = length = dtype = addressof = pointer = 0 ref = ptr_ = ptr = Descriptor.null - def __init__(self): pass + def __init__(self): """NULL""" DescriptorNULL = DescriptorNULL() -class Descriptor_s(Descriptor): +class DescriptorS(Descriptor): dclass_id = 1 @property @@ -170,22 +171,22 @@ def value(self): return dtypeToClass[self.dtype].fromDescriptor(self)._setTree(self.tree) -class Descriptor_d(Descriptor_s): +class DescriptorD(DescriptorS): dclass_id = 2 def __del__(self): _MdsShr.MdsFree1Dx(self.ptr, 0) -class Descriptor_xs(Descriptor_s): +class DescriptorXS(DescriptorS): dclass_id = 193 class _structure_class(_C.Structure): - _fields_ = Descriptor_s._structure_class._fields_ + [ + _fields_ = DescriptorS._structure_class._fields_ + [ ("l_length", _C.c_uint32)] def _new_structure(self, l_length=0, **kwarg): - super(Descriptor_xs, self)._new_structure(**kwarg) + super(DescriptorXS, self)._new_structure(**kwarg) self._structure.l_length = l_length PTR = _C.POINTER(_structure_class) null = _C.cast(0, PTR) @@ -196,7 +197,7 @@ def value(self): return Descriptor(self.pointer, self.__dict__)._setTree(self.tree).value -class Descriptor_xd(Descriptor_xs): +class DescriptorXD(DescriptorXS): dclass_id = 192 dtype_dsc = 24 @@ -204,12 +205,12 @@ def __del__(self): _MdsShr.MdsFree1Dx(self.ptr, 0) -class Descriptor_r(Descriptor_s): +class DescriptorR(DescriptorS): dclass_id = 194 class _structure_class(_C.Structure): _pack_ = _C.sizeof(_C.c_void_p) - _fields_ = Descriptor_s._structure_class._fields_ + [ + _fields_ = DescriptorS._structure_class._fields_ + [ ("ndesc", _C.c_ubyte), ("dscptrs", Descriptor.PTR*256)] PTR = _C.POINTER(_structure_class) @@ -218,7 +219,7 @@ class _structure_class(_C.Structure): # HINT: arrays -class Descriptor_a(Descriptor): +class DescriptorA(Descriptor): dclass_id = 4 class _structure_class(_C.Structure): @@ -234,7 +235,7 @@ class _structure_class(_C.Structure): ("coeff_and_bounds", _C.c_int32 * 24)] def _new_structure(self, arsize=0, **kwarg): - super(Descriptor_a, self)._new_structure(**kwarg) + super(DescriptorA, self)._new_structure(**kwarg) self._structure.arsize = arsize self._structure.aflags = 48 PTR = _C.POINTER(_structure_class) @@ -301,36 +302,36 @@ def bounds(self, value): self.aflags &= ~128 -class Descriptor_ca(Descriptor_a): +class DescriptorCA(DescriptorA): dclass_id = 195 @property def value(self): - xd = Descriptor_xd() + xd = DescriptorXD() _exc.checkStatus(_MdsShr.MdsDecompress(self.ptr, xd.ptr)) return xd._setTree(self.tree).value -class Descriptor_apd(Descriptor_a): +class DescriptorAPD(DescriptorA): dclass_id = 196 -dclassToClass = {Descriptor_s.dclass_id: Descriptor_s, - Descriptor_d.dclass_id: Descriptor_d, - Descriptor_xs.dclass_id: Descriptor_xs, - Descriptor_xd.dclass_id: Descriptor_xd, - Descriptor_r.dclass_id: Descriptor_r, - Descriptor_a.dclass_id: Descriptor_a, - Descriptor_ca.dclass_id: Descriptor_ca, - Descriptor_apd.dclass_id: Descriptor_apd} +dclassToClass = {DescriptorS.dclass_id: DescriptorS, + DescriptorD.dclass_id: DescriptorD, + DescriptorXS.dclass_id: DescriptorXS, + DescriptorXD.dclass_id: DescriptorXD, + DescriptorR.dclass_id: DescriptorR, + DescriptorA.dclass_id: DescriptorA, + DescriptorCA.dclass_id: DescriptorCA, + DescriptorAPD.dclass_id: DescriptorAPD} dtypeToClass = {} -def addDtypeToClass(Class): dtypeToClass[Class.dtype_id] = Class +def _add_dtype_to_class(cls): dtypeToClass[cls.dtype_id] = cls dtypeToArrayClass = {} -def addDtypeToArrayClass(Class): dtypeToArrayClass[Class.dtype_id] = Class +def _add_dtype_to_array_class(cls): dtypeToArrayClass[cls.dtype_id] = cls diff --git a/python/MDSplus/event.py b/python/MDSplus/event.py index cb28ec9051..54a6b49d02 100644 --- a/python/MDSplus/event.py +++ b/python/MDSplus/event.py @@ -27,7 +27,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) @@ -224,40 +224,40 @@ def queueEvent(event): return eventid.value @staticmethod - def stream(shot, signal, timeData, sampleData): - """Builds the payload for the MDS event STREAMING. This event will be received by a Node.js server + def stream(shot, signal, time_data, sample_data): + """Builds the payload for the MDS event STREAMING. This event will be received by a Node.js server that will serve web applications for waveform streaming @param shot: shot number @param signal: name of the signal. The choice of name is free @type signal: str - @param timeData: Time associated with samples + @param time_data: Time associated with samples @type signal: Data - @param sampleData: Data samples - @type sampleData: Data + @param sample_data: Data samples + @type sample_data: Data """ - if isinstance(timeData, _sca.Uint64) or isinstance(timeData, _arr.Uint64Array) or isinstance(timeData, _sca.Int64) or isinstance(timeData, _arr.Int64Array): - times = timeData.data() + if isinstance(time_data, _sca.Uint64) or isinstance(time_data, _arr.Uint64Array) or isinstance(time_data, _sca.Int64) or isinstance(time_data, _arr.Int64Array): + times = time_data.data() if _N.isscalar(times): times = [int(times)] else: times = times.astype(int).tolist() - isAbsoluteTime = 1 + is_absolute_time = 1 else: - times = timeData.data() + times = time_data.data() if _N.isscalar(times): times = [times.astype(float)] else: times = times.astype(float).tolist() - isAbsoluteTime = 0 - samples = sampleData.data() + is_absolute_time = 0 + samples = sample_data.data() if _N.isscalar(samples): samples = [samples.astype(float)] else: samples = samples.astype(float).tolist() - payloadDict = {'name': signal, 'shot':shot, 'samples': samples, 'times': times, - 'timestamp':0, 'absolute_time': isAbsoluteTime} + payload_dict = {'name': signal, 'shot':shot, 'samples': samples, 'times': times, + 'timestamp':0, 'absolute_time': is_absolute_time} - payload = json.dumps(payloadDict) + payload = json.dumps(payload_dict) Event.seteventRaw(signal, _N.uint8(bytearray(payload, 'utf8'))) def getQueue(self): diff --git a/python/MDSplus/magic.py b/python/MDSplus/magic.py index 7226ffbf9d..4b3c39154b 100644 --- a/python/MDSplus/magic.py +++ b/python/MDSplus/magic.py @@ -34,7 +34,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) @@ -63,27 +63,27 @@ def tcl(line, cell=None): for example: %tcl directory /full """ - toOut = [] - toError = [] + to_out = [] + to_error = [] - def doit(line, toOut, toError): + def doit(line, to_out, to_error): if len(line) == 0: return out, error = _dcl.tcl(line, return_out=True, return_error=True) if error is not None and len(str(error)) > 0: - toError.append(str(error)) + to_error.append(str(error)) if out is not None and len(str(out)) > 0: - toOut.append(str(out)) + to_out.append(str(out)) if cell is None: - doit(line, toOut, toError) + doit(line, to_out, to_error) else: for line in cell.split('\n'): - doit(line, toOut, toError) - if len(toOut) > 0: - print('\n'.join(toOut)) - if len(toError) > 0: - sys.stderr.write('\n'.join(toError+[''])) + doit(line, to_out, to_error) + if len(to_out) > 0: + print('\n'.join(to_out)) + if len(to_error) > 0: + sys.stderr.write('\n'.join(to_error+[''])) @register_line_cell_magic @@ -105,23 +105,23 @@ def tdi(line, cell=None): for example: %tdi _a=53+75 """ - toOut = [] - toError = [] + to_out = [] + to_error = [] - def doit(line, toOut, toError): + def doit(line, to_out, to_error): if len(line) == 0: return try: - toOut.append(str(_dat.tdi(line))) + to_out.append(str(_dat.tdi(line))) except Exception as e: - toError.append(str(e)) + to_error.append(str(e)) if cell is None: - doit(line, toOut, toError) + doit(line, to_out, to_error) else: for line in cell.split('\n'): - doit(cell, toOut, toError) - if len(toOut) > 0: - print('\n'.join(toOut)) - if len(toError) > 0: - sys.stderr.write('\n'.join(toError+[''])) + doit(cell, to_out, to_error) + if len(to_out) > 0: + print('\n'.join(to_out)) + if len(to_error) > 0: + sys.stderr.write('\n'.join(to_error+[''])) diff --git a/python/MDSplus/mdsarray.py b/python/MDSplus/mdsarray.py index da1379e8ae..d02b2124ba 100644 --- a/python/MDSplus/mdsarray.py +++ b/python/MDSplus/mdsarray.py @@ -38,6 +38,7 @@ def _mimport(name, level=1): _dat = _mimport('mdsdata') _scr = _mimport('mdsscalar') _cmd = _mimport('compound') +_exc = _mimport('mdsExceptions') class Array(_dat.Data): @@ -59,7 +60,7 @@ def __new__(cls, *value): elif isinstance(value, _C.Array): try: value = _N.ctypeslib.as_array(value) - except: + except Exception: pass elif isinstance(value, (int, _ver.long)): value = _N.array(value) @@ -117,7 +118,7 @@ def __getattribute__(self, name): return super(Array, self).__getattribute__(name) except AttributeError: if name == '_value': - raise Exception('_value undefined') + raise _exc.MdsException('_value undefined') try: return getattr(self._value, name) except AttributeError: @@ -205,7 +206,7 @@ def _descriptor(self): if not self._value.flags.c_contiguous: self._value = self._value.copy('C') value = self._value.T - d = _dsc.Descriptor_a() + d = _dsc.DescriptorA() d.scale = 0 d.digits = 0 d.dtype = self.dtype_id @@ -294,7 +295,7 @@ class Float32Array(Array): ntype = _N.float32 -_dsc.addDtypeToArrayClass(Float32Array) +_dsc._add_dtype_to_array_class(Float32Array) class Float64Array(Array): @@ -304,7 +305,7 @@ class Float64Array(Array): ntype = _N.float64 -_dsc.addDtypeToArrayClass(Float64Array) +_dsc._add_dtype_to_array_class(Float64Array) class Complex64Array(Array): @@ -313,7 +314,7 @@ class Complex64Array(Array): ntype = _N.complex64 -_dsc.addDtypeToArrayClass(Complex64Array) +_dsc._add_dtype_to_array_class(Complex64Array) class Complex128Array(Array): @@ -322,7 +323,7 @@ class Complex128Array(Array): ntype = _N.complex128 -_dsc.addDtypeToArrayClass(Complex128Array) +_dsc._add_dtype_to_array_class(Complex128Array) class Uint8Array(Array): @@ -338,7 +339,7 @@ def deserialize(self): return _dat.Data.deserialize(self) -_dsc.addDtypeToArrayClass(Uint8Array) +_dsc._add_dtype_to_array_class(Uint8Array) class Uint16Array(Array): @@ -348,7 +349,7 @@ class Uint16Array(Array): ntype = _N.uint16 -_dsc.addDtypeToArrayClass(Uint16Array) +_dsc._add_dtype_to_array_class(Uint16Array) class Uint32Array(Array): @@ -358,7 +359,7 @@ class Uint32Array(Array): ntype = _N.uint32 -_dsc.addDtypeToArrayClass(Uint32Array) +_dsc._add_dtype_to_array_class(Uint32Array) class Uint64Array(Array): @@ -368,7 +369,7 @@ class Uint64Array(Array): ntype = _N.uint64 -_dsc.addDtypeToArrayClass(Uint64Array) +_dsc._add_dtype_to_array_class(Uint64Array) class Int8Array(Array): @@ -384,7 +385,7 @@ def deserialize(self): return _dat.Data.deserialize(self) -_dsc.addDtypeToArrayClass(Int8Array) +_dsc._add_dtype_to_array_class(Int8Array) class Int16Array(Array): @@ -394,7 +395,7 @@ class Int16Array(Array): ntype = _N.int16 -_dsc.addDtypeToArrayClass(Int16Array) +_dsc._add_dtype_to_array_class(Int16Array) class Int32Array(Array): @@ -404,7 +405,7 @@ class Int32Array(Array): ntype = _N.int32 -_dsc.addDtypeToArrayClass(Int32Array) +_dsc._add_dtype_to_array_class(Int32Array) class Int64Array(Array): @@ -414,7 +415,7 @@ class Int64Array(Array): ntype = _N.int64 -_dsc.addDtypeToArrayClass(Int64Array) +_dsc._add_dtype_to_array_class(Int64Array) class FloatFArray(Float32Array): @@ -422,7 +423,7 @@ class FloatFArray(Float32Array): dtype_id = 10 -_dsc.addDtypeToArrayClass(FloatFArray) +_dsc._add_dtype_to_array_class(FloatFArray) class FloatDArray(Float64Array): @@ -430,7 +431,7 @@ class FloatDArray(Float64Array): dtype_id = 11 -_dsc.addDtypeToArrayClass(FloatDArray) +_dsc._add_dtype_to_array_class(FloatDArray) class ComplexFArray(Complex64Array): @@ -438,7 +439,7 @@ class ComplexFArray(Complex64Array): dtype_id = 12 -_dsc.addDtypeToArrayClass(ComplexFArray) +_dsc._add_dtype_to_array_class(ComplexFArray) class ComplexDArray(Complex128Array): @@ -446,7 +447,7 @@ class ComplexDArray(Complex128Array): dtype_id = 13 -_dsc.addDtypeToArrayClass(ComplexDArray) +_dsc._add_dtype_to_array_class(ComplexDArray) class StringArray(Array): @@ -487,7 +488,7 @@ def __add__(self, y): return self.execute('$//$', self, y) -_dsc.addDtypeToArrayClass(StringArray) +_dsc._add_dtype_to_array_class(StringArray) class Uint128Array(Array): @@ -498,7 +499,7 @@ def __init__(self): raise TypeError("Uint128Array is not yet supported") -_dsc.addDtypeToArrayClass(Uint128Array) +_dsc._add_dtype_to_array_class(Uint128Array) class Int128Array(Array): @@ -509,7 +510,7 @@ def __init__(self): raise TypeError("Int128Array is not yet supported") -_dsc.addDtypeToArrayClass(Int128Array) +_dsc._add_dtype_to_array_class(Int128Array) class FloatGArray(Float64Array): @@ -517,7 +518,7 @@ class FloatGArray(Float64Array): dtype_id = 27 -_dsc.addDtypeToArrayClass(FloatGArray) +_dsc._add_dtype_to_array_class(FloatGArray) class ComplexGArray(Complex128Array): @@ -525,7 +526,7 @@ class ComplexGArray(Complex128Array): dtype_id = 29 -_dsc.addDtypeToArrayClass(ComplexGArray) +_dsc._add_dtype_to_array_class(ComplexGArray) _apd = _mimport('apd') _cmp = _mimport('compound') diff --git a/python/MDSplus/mdsdata.py b/python/MDSplus/mdsdata.py index e8df4e02db..c08fbc2154 100644 --- a/python/MDSplus/mdsdata.py +++ b/python/MDSplus/mdsdata.py @@ -27,7 +27,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) @@ -56,10 +56,10 @@ def __get__(self, inst, cls): def __init__(self, method): self.method = method - def static(mself, self, *args, **kwargs): - if self is None: + def static(self, obj, *args, **kwargs): + if obj is None: return None - return mself.method(Data(self), *args, **kwargs) + return self.method(Data(obj), *args, **kwargs) def _unwrap(args): @@ -185,7 +185,7 @@ def getXYSignal(self, x=None, xmin=None, xmax=None, num=2048): num = _C.c_int32(num) xmin = Data(xmin) xmax = Data(xmax) - xd = _dsc.Descriptor_xd() + xd = _dsc.DescriptorXD() if self.tree is None: status = _MdsMisc. GetXYSignalXd(self.ref, Data.byref( x), Data.byref(xmin), Data.byref(xmax), num, xd.ref) @@ -830,7 +830,7 @@ def serialize(self): """Return Uint8Array binary representation. @rtype: Uint8Array """ - xd = _dsc.Descriptor_xd() + xd = _dsc.DescriptorXD() _exc.checkStatus( _MdsShr.MdsSerializeDscOut(self.ref, xd.ref)) @@ -845,7 +845,7 @@ def deserialize(bytes): """ if len(bytes) == 0: # short cut if setevent did not send array return _apd.List([]) - xd = _dsc.Descriptor_xd() + xd = _dsc.DescriptorXD() _exc.checkStatus( _MdsShr.MdsSerializeDscIn(_C.c_void_p(bytes.ctypes.data), xd.ref)) @@ -860,7 +860,7 @@ class EmptyData(Data): dtype_id = 24 """No Value aka *""" - def __init__(self, *value): pass + def __init__(self, *value): """empty""" def decompile(self): return "*" @@ -902,12 +902,9 @@ def setDescAt(self, idx, value): self._descs[idx] = tuple(Data(val) for val in value) self._setTree(*value) else: - last = idx if value is None: if len(self._descs) > idx: self._descs[idx] = None - else: - last = -1 else: diff = 1+idx-len(self._descs) if diff > 0: diff --git a/python/MDSplus/mdsdcl.py b/python/MDSplus/mdsdcl.py index 31ada5618d..c81b85b2b7 100644 --- a/python/MDSplus/mdsdcl.py +++ b/python/MDSplus/mdsdcl.py @@ -23,18 +23,17 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from __future__ import print_function +import ctypes as _C import sys as _sys def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) -import ctypes as _C - _ver = _mimport('version') _exc = _mimport('mdsExceptions') _dsc = _mimport('descriptor') @@ -42,10 +41,10 @@ def _mimport(name, level=1): try: _mdsdcl = _ver.load_library('Mdsdcl') _mdsdcl. mdsdcl_do_command_dsc.argtypes = [ - _C.c_char_p, _dsc.Descriptor_xd.PTR, _dsc.Descriptor_xd.PTR] + _C.c_char_p, _dsc.DescriptorXD.PTR, _dsc.DescriptorXD.PTR] _mdsdcl._mdsdcl_do_command_dsc.argtypes = [ - _C.c_void_p, _C.c_char_p, _dsc.Descriptor_xd.PTR, _dsc.Descriptor_xd.PTR] -except: + _C.c_void_p, _C.c_char_p, _dsc.DescriptorXD.PTR, _dsc.DescriptorXD.PTR] +except Exception: def dcl(*a, **kw): raise _exc.LibNOTFOU("Mdsdcl") else: @@ -63,9 +62,9 @@ def dcl(command, return_out=False, return_error=False, raise_exception=False, tr @type setcommand: str @rtype: str / tuple / None """ - xd_error = _dsc.Descriptor_xd() + xd_error = _dsc.DescriptorXD() error_p = xd_error.ptr - xd_output = _dsc.Descriptor_xd() + xd_output = _dsc.DescriptorXD() out_p = xd_output.ptr _exc.checkStatus(_mdsdcl.mdsdcl_do_command_dsc( _ver.tobytes('set command %s' % (setcommand,)), error_p, out_p)) diff --git a/python/MDSplus/mdsscalar.py b/python/MDSplus/mdsscalar.py index 0510698ece..c954399be2 100644 --- a/python/MDSplus/mdsscalar.py +++ b/python/MDSplus/mdsscalar.py @@ -27,7 +27,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) @@ -121,7 +121,7 @@ def mdsdtype(self): @property def _descriptor(self): - d = _dsc.Descriptor_s() + d = _dsc.DescriptorS() d.length = self._value.nbytes d.dtype = self.dtype_id array = _N.array(self._value) @@ -245,7 +245,7 @@ class Float32(Scalar): _ntype = _N.float32 -_dsc.addDtypeToClass(Float32) +_dsc._add_dtype_to_class(Float32) class Float64(Scalar): @@ -255,7 +255,7 @@ class Float64(Scalar): _ntype = _N.float64 -_dsc.addDtypeToClass(Float64) +_dsc._add_dtype_to_class(Float64) class Complex64(Scalar): @@ -265,7 +265,7 @@ class Complex64(Scalar): _ntype = _N.complex64 -_dsc.addDtypeToClass(Complex64) +_dsc._add_dtype_to_class(Complex64) class Complex128(Scalar): @@ -275,7 +275,7 @@ class Complex128(Scalar): _ntype = _N.complex128 -_dsc.addDtypeToClass(Complex128) +_dsc._add_dtype_to_class(Complex128) class Uint8(Scalar): @@ -285,7 +285,7 @@ class Uint8(Scalar): _ntype = _N.uint8 -_dsc.addDtypeToClass(Uint8) +_dsc._add_dtype_to_class(Uint8) class Uint16(Scalar): @@ -295,7 +295,7 @@ class Uint16(Scalar): _ntype = _N.uint16 -_dsc.addDtypeToClass(Uint16) +_dsc._add_dtype_to_class(Uint16) class Uint32(Scalar): @@ -305,7 +305,7 @@ class Uint32(Scalar): _ntype = _N.uint32 -_dsc.addDtypeToClass(Uint32) +_dsc._add_dtype_to_class(Uint32) class Uint64(Scalar): @@ -337,7 +337,7 @@ def _getTime(self): time = property(_getTime) -_dsc.addDtypeToClass(Uint64) +_dsc._add_dtype_to_class(Uint64) class Int8(Uint8): @@ -347,7 +347,7 @@ class Int8(Uint8): _ntype = _N.int8 -_dsc.addDtypeToClass(Int8) +_dsc._add_dtype_to_class(Int8) class Int16(Uint16): @@ -357,7 +357,7 @@ class Int16(Uint16): _ntype = _N.int16 -_dsc.addDtypeToClass(Int16) +_dsc._add_dtype_to_class(Int16) class Int32(Uint32): @@ -367,7 +367,7 @@ class Int32(Uint32): _ntype = _N.int32 -_dsc.addDtypeToClass(Int32) +_dsc._add_dtype_to_class(Int32) class Int64(Uint64): @@ -377,7 +377,7 @@ class Int64(Uint64): _ntype = _N.int64 -_dsc.addDtypeToClass(Int64) +_dsc._add_dtype_to_class(Int64) class FloatF(Float32): @@ -385,7 +385,7 @@ class FloatF(Float32): dtype_id = 10 -_dsc.addDtypeToClass(FloatF) +_dsc._add_dtype_to_class(FloatF) class FloatD(Float64): @@ -393,7 +393,7 @@ class FloatD(Float64): dtype_id = 11 -_dsc.addDtypeToClass(FloatD) +_dsc._add_dtype_to_class(FloatD) class ComplexF(Complex64): @@ -401,7 +401,7 @@ class ComplexF(Complex64): dtype_id = 12 -_dsc.addDtypeToClass(ComplexF) +_dsc._add_dtype_to_class(ComplexF) class ComplexD(Complex128): @@ -409,7 +409,7 @@ class ComplexD(Complex128): dtype_id = 13 -_dsc.addDtypeToClass(ComplexD) +_dsc._add_dtype_to_class(ComplexD) class String(Scalar): @@ -424,7 +424,7 @@ def __init__(self, value): @property def _descriptor(self): - d = _dsc.Descriptor_s() + d = _dsc.DescriptorS() d.length = len(self) d.dtype = self.dtype_id d.pointer = _C.cast(_C.c_char_p(_ver.tobytes(str(self))), _C.c_void_p) @@ -461,7 +461,7 @@ def __repr__(self): return repr(_ver.tostr(self._value)) -_dsc.addDtypeToClass(String) +_dsc._add_dtype_to_class(String) class Uint128(Scalar): @@ -472,7 +472,7 @@ def __init__(self): raise TypeError("Uint128 is not yet supported") -_dsc.addDtypeToClass(Uint128) +_dsc._add_dtype_to_class(Uint128) class Int128(Uint128): @@ -483,7 +483,7 @@ def __init__(self): raise TypeError("Int128 is not yet supported") -_dsc.addDtypeToClass(Int128) +_dsc._add_dtype_to_class(Int128) class FloatG(Float64): @@ -491,7 +491,7 @@ class FloatG(Float64): dtype_id = 27 -_dsc.addDtypeToClass(FloatG) +_dsc._add_dtype_to_class(FloatG) class ComplexG(Complex128): @@ -499,7 +499,7 @@ class ComplexG(Complex128): dtype_id = 29 -_dsc.addDtypeToClass(ComplexG) +_dsc._add_dtype_to_class(ComplexG) class Pointer(Scalar): @@ -525,7 +525,7 @@ def fromDescriptor(cls, d): return cls(value.value, is64) -_dsc.addDtypeToClass(Pointer) +_dsc._add_dtype_to_class(Pointer) class Ident(_dat.TreeRef, _dat.Data): @@ -548,7 +548,7 @@ def assign(self, value): @property def _descriptor(self): - d = _dsc.Descriptor_s() + d = _dsc.DescriptorS() d.dtype = self.dtype_id d.length = len(self.name) d.pointer = _C.cast(_C.c_char_p(_ver.tobytes(self.name)), _C.c_void_p) @@ -559,6 +559,6 @@ def fromDescriptor(cls, d): return cls(_ver.tostr(_C.cast(d.pointer, _C.POINTER(_C.c_char*d.length)).contents.value)) -_dsc.addDtypeToClass(Ident) +_dsc._add_dtype_to_class(Ident) _cmp = _mimport('compound') diff --git a/python/MDSplus/modpython.py b/python/MDSplus/modpython.py index 6fd0a16b74..633d6c5582 100644 --- a/python/MDSplus/modpython.py +++ b/python/MDSplus/modpython.py @@ -115,7 +115,7 @@ def handler(req): os.putenv('UDP_EVENTS', 'yes') if "EVENT_SERVER" in opts: os.putenv("mds_event_server", opts['EVENT_SERVER']) - except: + except Exception: pass os.putenv('UDP_EVENTS', 'yes') event = req.path_info.rsplit('/')[-1] @@ -123,27 +123,27 @@ def handler(req): timeout = 60 try: timeout = int(args['timeout'][-1]) - except: + except Exception: pass try: event = args['event'][-1] - except: + except Exception: pass if 'handler' in args: - specialHandler = __import__(args['handler'][-1]) - if hasattr(specialHandler, 'handler'): - specialHandler = specialHandler.handler + special_handler = __import__(args['handler'][-1]) + if hasattr(special_handler, 'handler'): + special_handler = special_handler.handler else: - raise(Exception(str(dir(specialHandler)))) + raise Exception(str(dir(special_handler))) else: - specialHandler = None + special_handler = None e = myevent(event, timeout) e.join() req.headers_out['Cache-Control'] = 'no-store, no-cache, must-revalidate' req.headers_out['Pragma'] = 'no-cache' req.content_type = "text/xml" - if specialHandler is not None: - result = specialHandler(req, e) + if special_handler is not None: + result = special_handler(req, e) if result is not None: return result if e.exception is None: diff --git a/python/MDSplus/scope.py b/python/MDSplus/scope.py index 39b45d95b2..fa46fa280c 100644 --- a/python/MDSplus/scope.py +++ b/python/MDSplus/scope.py @@ -27,7 +27,7 @@ def _mimport(name, level=1): try: return __import__(name, globals(), level=level) - except: + except Exception: return __import__(name, globals()) diff --git a/python/MDSplus/tree.py b/python/MDSplus/tree.py index 6bbc8c796a..4a7a64b21a 100644 --- a/python/MDSplus/tree.py +++ b/python/MDSplus/tree.py @@ -459,7 +459,7 @@ def getFileName(self, tree=None, shot=None): """Return file path. @rtype: str """ - xd = _dsc.Descriptor_xd() + xd = _dsc.DescriptorXD() if tree is None: treeref = None else: @@ -949,9 +949,9 @@ def getTimeContext(self): """Get time context for retrieving segmented records (begin,end,delta) @rtype: tuple """ - begin = _dsc.Descriptor_xd() - end = _dsc.Descriptor_xd() - delta = _dsc.Descriptor_xd() + begin = _dsc.DescriptorXD() + end = _dsc.DescriptorXD() + delta = _dsc.DescriptorXD() if isinstance(self, (Tree,)): begin._setTree(self) end._setTree(self) @@ -1268,7 +1268,7 @@ def ORIGINAL_PART_NAME(self): @property def _descriptor(self): """Return a MDSplus descriptor""" - d = _dsc.Descriptor_s() + d = _dsc.DescriptorS() d.length = 4 d.dtype = self.dtype_id d.pointer = _C.cast(_C.pointer(self._nid), _C.c_void_p) @@ -1865,7 +1865,7 @@ def doMethod(self, method, *args): @rtype: None """ arglist = [self.ctx] - xd = _dsc.Descriptor_xd() + xd = _dsc.DescriptorXD() argsobj = [self, _scr.String(method)] arglist += list(map(_dat.Data.byref, argsobj)) arglist.append(len(args)) @@ -1936,7 +1936,7 @@ def getRecord(self, *altvalue): @return: data stored in this node @rtype: Data """ - xd = _dsc.Descriptor_xd() + xd = _dsc.DescriptorXD() status = _TreeShr._TreeGetRecord(self.ctx, self._nid, xd.ref) if (status & 1): return xd._setTree(self.tree).value @@ -1983,7 +1983,7 @@ def getExtendedAttribute(self, name): attribute has no data @rtype: MDSplus data type """ - xd = _dsc.Descriptor_xd() + xd = _dsc.DescriptorXD() status = _TreeShr._TreeGetXNci(self.ctx, self.nid, _C.c_char_p(_ver.tobytes( @@ -2219,8 +2219,8 @@ def getSegment(self, idx): @return: Data segment @rtype: Signal | None """ - val = _dsc.Descriptor_xd()._setTree(self.tree) - dim = _dsc.Descriptor_xd()._setTree(self.tree) + val = _dsc.DescriptorXD()._setTree(self.tree) + dim = _dsc.DescriptorXD()._setTree(self.tree) try: _exc.checkStatus( _TreeShr._TreeGetSegment(self.ctx, @@ -2245,7 +2245,7 @@ def getSegmentDim(self, idx): @return: Segment dimension @rtype: Dimension """ - dim = _dsc.Descriptor_xd()._setTree(self.tree) + dim = _dsc.DescriptorXD()._setTree(self.tree) try: _exc.checkStatus( _TreeShr._TreeGetSegment(self.ctx, @@ -2258,8 +2258,8 @@ def getSegmentDim(self, idx): return dim.value def getSegmentLimits(self, idx): - start = _dsc.Descriptor_xd()._setTree(self.tree) - end = _dsc.Descriptor_xd()._setTree(self.tree) + start = _dsc.DescriptorXD()._setTree(self.tree) + end = _dsc.DescriptorXD()._setTree(self.tree) _exc.checkStatus( _TreeShr._TreeGetSegmentLimits(self.ctx, self._nid, @@ -2273,7 +2273,7 @@ def getSegmentLimits(self, idx): def getSegmentList(self, start, end): start, end = map(_dat.Data, (start, end)) - xd = _dsc.Descriptor_xd()._setTree(self.tree) + xd = _dsc.DescriptorXD()._setTree(self.tree) _exc.checkStatus( _XTreeShr._XTreeGetSegmentList(self.ctx, self._nid, @@ -2286,7 +2286,7 @@ def getSegmentScale(self): """sets the scale expression of a segmetned Node @rtype: expression for the data field; should contain $VALUE """ - xd = _dsc.Descriptor_xd()._setTree(self.tree) + xd = _dsc.DescriptorXD()._setTree(self.tree) _exc.checkStatus( _TreeShr._TreeGetSegmentScale(self.ctx, self._nid, @@ -2295,8 +2295,8 @@ def getSegmentScale(self): def getSegmentTimes(self): num = _C.c_int32(0) - start = _dsc.Descriptor_xd()._setTree(self.tree) - end = _dsc.Descriptor_xd()._setTree(self.tree) + start = _dsc.DescriptorXD()._setTree(self.tree) + end = _dsc.DescriptorXD()._setTree(self.tree) _exc.checkStatus( _TreeShr._TreeGetSegmentTimesXd(self.ctx, self._nid, @@ -3055,7 +3055,7 @@ def __str__(self): @property def _descriptor(self): - d = _dsc.Descriptor_s() + d = _dsc.DescriptorS() d.length = len(self.tree_path) d.dtype = self.dtype_id d.pointer = _C.cast(_C.c_char_p( @@ -3249,7 +3249,7 @@ def __init__(self, target=None, is_property=False, **opt): def __call__(self, method): if hasattr(self, 'target'): - raise Exception("cached_property.target already set") + raise _exc.MdsException("cached_property.target already set") self.target = property(method) return self @@ -3337,7 +3337,7 @@ def __new__(cls, *target, **opt): def __call__(self, target): if hasattr(self, 'target'): - raise Exception("mdsrecord.target already set") + raise _exc.MdsException("mdsrecord.target already set") self.target = target if self.cached is None: return self @@ -3377,7 +3377,7 @@ def bytes(node): return _ver.tobytes(node.data()) @staticmethod def bytes_list(node): - return [_ver.tostr(x).rstrip() + return [_ver.tobytes(x).rstrip() for x in node.data().flatten()] @staticmethod @@ -3507,7 +3507,7 @@ def _debugDevice(dev): return dev from types import FunctionType - def dummy(self, *args, **kvargs): pass + def dummy(self, *args, **kvargs): """dummy""" db = {} for d in dev.mro()[-5::-1]: # mro[-4] is Device for k, v in d.__dict__.items(): @@ -3535,7 +3535,7 @@ def _mimport(loc, glob, filename, name=None): try: device = __import__(filename, glob, fromlist=[ name], level=1).__getattribute__(name) - except: + except Exception: device = __import__(filename, glob, fromlist=[ name]).__getattribute__(name) if debug: @@ -3568,7 +3568,7 @@ def __new__(cls, node, tree=None, head=0, *a, **kw): head = TreeNode( node.conglomerate_nids.nid_number[0], node.tree, 0) return head.getDevice(head) - except: + except Exception: raise TypeError("Cannot create instances of Device class") elif not cls in cls.__initialized: cls.part_names = tuple(elt['path'] for elt in cls.parts) @@ -3641,7 +3641,7 @@ def fullhelp_str(self): msg.append('\n%s' % ('-'*64)) return '\n'.join(msg) except AttributeError as e: - raise Exception(e.message) + raise _exc.MdsException(e.message) def fullhelp(self): print(self.fullhelp_str) @@ -3691,7 +3691,7 @@ def __setattr__(self, name, value): @type value: varied @rtype: None """ - def isInDicts(name, cls): + def is_in_dicts(name, cls): for c in cls.mro()[:-1]: if name in c.__dict__: return True @@ -3703,7 +3703,7 @@ def isInDicts(name, cls): self.tree, head).record = value elif (name.startswith('_') or name in self.__dict__ - or isInDicts(name, self.__class__) + or is_in_dicts(name, self.__class__) or isinstance(stack()[1][0].f_locals.get('self', None), Device)): super(Device, self).__setattr__(name, value) else: @@ -3787,7 +3787,7 @@ def Add(cls, tree, name, add_source=False): on (i.e. write_once). """ if cls is Device: - raise Exception("Cannot add super class Device.") + raise _exc.MdsException("Cannot add super class Device.") parent = tree if isinstance(tree, TreeNode): tree = tree.tree @@ -3846,14 +3846,14 @@ def dw_setup(self, *args): """ try: _widgets = _mimport('widgets') - import os import gtk + import gtk.glade + import os import inspect import threading import sys - import gtk.glade - class gtkMain(threading.Thread): + class gtk_main(threading.Thread): def run(self): gtk.main() @@ -3877,12 +3877,12 @@ def write(self, string): str(self)+' - '+str(self.tree)) _widgets.MDSplusWidget.doToAll(window, "reset") except Exception as exc: - raise Exception("No setup available, %s" % (str(exc),)) + raise _exc.MdsException("No setup available, %s" % (str(exc),)) window.connect("destroy", self.onSetupWindowClose) window.show_all() if Device.gtkThread is None or not Device.gtkThread.isAlive(): - Device.gtkThread = gtkMain() + Device.gtkThread = gtk_main() Device.gtkThread.start() return _exc.MDSplusSUCCESS.status DW_SETUP = dw_setup @@ -4029,6 +4029,5 @@ def PyDevice(cls, module, model=None): ############# dtype to classes ################################## -# _dsc.dtypeToClass[TreeNode.dtype_id] = TreeNode _dsc.dtypeToClass[TreePath.dtype_id] = TreePath diff --git a/python/MDSplus/version.py b/python/MDSplus/version.py index 43a9a9614b..66025bb199 100644 --- a/python/MDSplus/version.py +++ b/python/MDSplus/version.py @@ -28,6 +28,7 @@ Its purpose is to supply tools that are used to generate version specific code. Goal is to generate code that work on both python2x and python3x. """ +from types import GeneratorType as generator # analysis:ignore from numpy import generic as npscalar from numpy import ndarray as nparray from numpy import string_ as npbytes @@ -75,28 +76,26 @@ def load_library(name): if isdarwin: return C.CDLL('lib%s.dylib' % name) return C.CDLL('lib%s.so' % name) - except: + except Exception: pass print("Issues loading %s, trying find_library" % name) from ctypes.util import find_library try: libnam = find_library(name) - except: + except Exception: raise ImportError("Could not find library: %s" % (name,)) if libnam is None: raise ImportError("Could not find library: %s" % (name,)) try: return C.CDLL(libnam) - except: + except Exception: pass try: return C.CDLL(os.path.basename(libnam)) - except: + except Exception: raise ImportError('Could not load library: %s' % (name,)) -from types import GeneratorType as generator # analysis:ignore - # substitute missing builtins if has_long: long = long @@ -135,7 +134,7 @@ def superdir(cls, self=None): def get_attrs(obj): try: return obj.__dict__.keys() - except: + except Exception: return [] attrs = set() attrs.update(get_attrs(cls)) @@ -166,7 +165,7 @@ def get_attrs(obj): def _decode(string): try: return string.decode('utf-8', 'backslashreplace') - except: + except Exception: return string.decode('CP1252', 'backslashreplace') diff --git a/python/MDSplus/wsgi/doPlot.py b/python/MDSplus/wsgi/doPlot.py index 3d8e7e0158..85bbdf8ff2 100644 --- a/python/MDSplus/wsgi/doPlot.py +++ b/python/MDSplus/wsgi/doPlot.py @@ -23,7 +23,7 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # -from MDSplus import Data, TdiCompile, version, String, Descriptor_xd +from MDSplus import Data, TdiCompile, version, String, DescriptorXD import os import sys import ctypes