From f7553ebafd32536cc569348697039de86bf3f56c Mon Sep 17 00:00:00 2001 From: Gilles DAVID Date: Thu, 30 Mar 2017 14:11:52 +0200 Subject: [PATCH] Porting to Python 3 (1st draft) --- doc/tut/medcoupling/partition.py | 2 +- doc/tut/medcoupling/pyfunctions/functions.py | 38 ++++----- doc/tut/medcoupling/pyfunctions/lagrange.py | 21 +++-- doc/tut/medcoupling/pyfunctions/plotter.py | 2 +- doc/tut/medcoupling/test-paravis.py | 20 ++--- doc/tut/medcoupling/testmed_gendata.py | 10 +-- doc/tut/medcoupling/testmed_lena.py | 8 +- doc/tut/medcoupling/testmed_simple.py | 6 +- doc/tut/medcoupling/testpil.py | 14 ++-- doc/tut/medloader/cmesh.py | 10 +-- doc/tut/medloader/explore.py | 10 +-- doc/tut/medloader/manage.py | 22 +++--- doc/tut/medloader/testamel.py | 2 +- src/MEDCalc/cmp/MEDPresentation.cxx | 16 +++- src/MEDCalc/cmp/test_medcalc_components.py | 48 ++++++------ src/MEDCalc/exe/image2med/image2med.py | 6 +- src/MEDCalc/gui/MEDEventListener_i.hxx | 1 + src/MEDCalc/gui/MEDModule.hxx | 1 + src/MEDCalc/gui/MEDWidgetHelper.hxx | 1 + src/MEDCalc/gui/PresentationController.hxx | 3 +- src/MEDCalc/gui/ProcessingController.hxx | 1 + src/MEDCalc/gui/WorkspaceController.cxx | 4 +- src/MEDCalc/gui/WorkspaceController.hxx | 2 +- src/MEDCalc/gui/XmedConsoleDriver.cxx | 2 +- src/MEDCalc/test/gui/test_qttesting.py | 2 +- src/MEDCalc/test/tui/contour.py | 2 +- src/MEDCalc/tui/__init__.py | 78 +++++++++---------- src/MEDCalc/tui/fieldproxy.py | 30 +++---- src/MEDCalc/tui/medconsole.py | 20 ++--- src/MEDCalc/tui/medevents.py | 6 +- src/MEDCalc/tui/medimages.py | 2 +- src/MEDCalc/tui/medio.py | 2 +- src/MEDCalc/tui/medpresentation.py | 11 +-- src/MEDCalculator/Swig/MEDCalculator.i | 7 +- .../Swig/MEDCalculatorBasicsTest.py | 38 ++++----- .../Swig/MEDCalculatorTypemaps.i | 11 ++- src/MEDCalculator/Swig/SPythonInterpreter.cxx | 6 +- src/MEDCalculator/Swig/SPythonParser.cxx | 10 ++- src/MEDCalculator/Swig/test.spy | 2 +- src/MEDCalculator/Swig/test2.spy | 4 +- .../MEDCouplingCorbaSwigTest.py | 6 +- .../MEDCouplingCorbaSwigTestClt.py | 6 +- .../TestMEDCouplingCorbaClt.py | 10 +-- 43 files changed, 262 insertions(+), 241 deletions(-) diff --git a/doc/tut/medcoupling/partition.py b/doc/tut/medcoupling/partition.py index 4952cbc45..624000a47 100644 --- a/doc/tut/medcoupling/partition.py +++ b/doc/tut/medcoupling/partition.py @@ -76,4 +76,4 @@ numberOf3DVolSharing=revDescI.deltaShiftIndex() ids2D=numberOf3DVolSharing.findIdsEqual(1) skin_V650=m2D[ids2D] # We can check if the two skins are identical -print "Are two meshes equal between V660 and V650 ?",skin.isEqual(skin_V650,1e-12) +print("Are two meshes equal between V660 and V650 ?",skin.isEqual(skin_V650,1e-12)) diff --git a/doc/tut/medcoupling/pyfunctions/functions.py b/doc/tut/medcoupling/pyfunctions/functions.py index 2ecb5c95a..a39d0934c 100755 --- a/doc/tut/medcoupling/pyfunctions/functions.py +++ b/doc/tut/medcoupling/pyfunctions/functions.py @@ -31,7 +31,7 @@ class Function: # The argument can be a scalar or a list, we have to check # that first. if isIterable(x): - y = map(self,x) + y = list(map(self,x)) else: y = self.function(x, **self.kwargs) return y @@ -44,7 +44,7 @@ def isIterable(x): try: len(x) return True - except TypeError, e: + except TypeError as e: return False # @@ -140,7 +140,7 @@ class FuncPorte(Function): y=1 return y -import lagrange +from . import lagrange class FuncLagrange(Function): def __init__(self,points): """ @@ -172,12 +172,12 @@ def TEST_Function(): x=2 y_ref = 3.*x+7. y_res = f(x) - print y_ref - print y_res + print(y_ref) + print(y_res) if y_ref != y_res: - print "ERR" + print("ERR") else: - print "OK" + print("OK") def TEST_Function_withIterable(): f=MyFunction(a=3.,b=1.) @@ -186,42 +186,42 @@ def TEST_Function_withIterable(): arrY = f(arrX) arrY_ref = [1., 4., 7., 10.] - print "arrY res =%s"%arrY - print "arrY ref =%s"%arrY_ref + print("arrY res =%s"%arrY) + print("arrY ref =%s"%arrY_ref) def TEST_FuncConique(): f=FuncConique(xlimit=0.3) - from plotter import plot + from .plotter import plot plot(f) def TEST_FuncChapeau(): f=FuncChapeau(xlimit=0.3) - from plotter import plot + from .plotter import plot plot(f) def TEST_FuncStiffExp(): f=FuncStiffExp(xlimit=0.3,stiffness=20.) - from plotter import plot + from .plotter import plot plot(f) def TEST_FuncCosinus(): f=FuncCosinus(nbPeriods=20) - from plotter import plot + from .plotter import plot plot(f, step=0.001) def TEST_FuncStiffPulse(): f=FuncStiffPulse(xlimit=0.3,stiffness=50,nbPeriods=15) - from plotter import plot + from .plotter import plot plot(f, step=0.001) def TEST_FuncHeaviside(): f=FuncHeaviside(xlimit=0.3) - from plotter import plot + from .plotter import plot plot(f) def TEST_FuncPorte(): f=FuncPorte(xinf=0.3,xsup=0.4) - from plotter import plot + from .plotter import plot plot(f) def TEST_customize_01(): @@ -233,7 +233,7 @@ def TEST_customize_01(): y=5*f(x)+2 return y - from plotter import plot + from .plotter import plot plot(myfunc, step=0.001) def TEST_customize_02(): @@ -245,13 +245,13 @@ def TEST_customize_02(): y=1-f(x) return y - from plotter import plot + from .plotter import plot plot(myfunc) def TEST_FuncLagrange(): points = {0.:5, 0.2:10, 0.9:10, 0.6:21, 1:8} f=FuncLagrange(points) - from plotter import plot + from .plotter import plot plot(f) if __name__ == "__main__": diff --git a/doc/tut/medcoupling/pyfunctions/lagrange.py b/doc/tut/medcoupling/pyfunctions/lagrange.py index a98d159ba..3913b1c0e 100755 --- a/doc/tut/medcoupling/pyfunctions/lagrange.py +++ b/doc/tut/medcoupling/pyfunctions/lagrange.py @@ -30,10 +30,10 @@ def lagrange(points): tmp = scipy.poly1d([0]) result=scipy.poly1d([0]) - for i in points.keys(): + for i in points: numerator=scipy.poly1d([1]) denom = 1.0 - for j in points.keys(): + for j in points: if (i != j): tmp = scipy.poly1d([1,-j]) numerator = numerator * tmp @@ -60,8 +60,7 @@ def points_usingarray(arrX,arrY): def sortdict(points): # Sort this dictionary by keys and returns 2 lists, the list of X # and the list of Y, the whole ordered by X - keys = points.keys() - keys.sort() + keys = sorted(list(points.keys())) return keys, [points[key] for key in keys] import pylab @@ -72,7 +71,7 @@ def plot(function, start=0., stop=1., step=0.01): """ arrX=numpy.arange(start, stop, step, dtype='float64') # function is a callable - arrY=map(function,arrX) + arrY=list(map(function,arrX)) pylab.plot(arrX, arrY) pylab.show() @@ -82,13 +81,13 @@ def plot(function, start=0., stop=1., step=0.01): def TEST_lagrange_01(): input = {0.:5, 0.2:10, 0.9:10, 0.6:21, 1:8} polynom = lagrange(input) - print polynom + print(polynom) plot(function=polynom, start=0., stop=1., step=0.001) def TEST_lagrange_02(): input = {0.:0., 0.5:1., 1.:0.} polynom = lagrange(input) - print polynom + print(polynom) plot(function=polynom, start=0., stop=1., step=0.001) # --- @@ -98,7 +97,7 @@ def TEST_lagrange_usingarrays_01(): arrY = [5, 10, 10, 21, 8] input = points_usingarray(arrX,arrY) polynom = lagrange(input) - print polynom + print(polynom) plot(function=polynom, start=0., stop=1., step=0.001) # Another example using numpy @@ -108,7 +107,7 @@ def TEST_lagrange_usingarrays_02(): arrY[3]=2 input = points_usingarray(arrX,arrY) polynom = lagrange(input) - print polynom + print(polynom) plot(function=polynom, start=0., stop=1., step=0.001) # --- @@ -121,7 +120,7 @@ def TEST_lagrange_usingfunction_01(): arrY=numpy.cos(10*arrX) input = points_usingarray(arrX,arrY) polynom = lagrange(input) - print polynom + print(polynom) plot(function=polynom, start=0., stop=1., step=0.001) # General method @@ -137,7 +136,7 @@ def TEST_lagrange_usingfunction_01(): arrX=numpy.arange(start=0., stop=1., step=0.1, dtype='float64') input = points_usingfunction(arrX,chapeau) polynom = lagrange(input) - print polynom + print(polynom) plot(function=polynom, start=0., stop=1., step=0.001) diff --git a/doc/tut/medcoupling/pyfunctions/plotter.py b/doc/tut/medcoupling/pyfunctions/plotter.py index e414655b1..7c52b7587 100644 --- a/doc/tut/medcoupling/pyfunctions/plotter.py +++ b/doc/tut/medcoupling/pyfunctions/plotter.py @@ -26,6 +26,6 @@ def plot(function, start=0., stop=1., step=0.01): """ arrX=numpy.arange(start, stop, step, dtype='float64') # function is a callable - arrY=map(function,arrX) + arrY=list(map(function,arrX)) pylab.plot(arrX, arrY) pylab.show() diff --git a/doc/tut/medcoupling/test-paravis.py b/doc/tut/medcoupling/test-paravis.py index d0f59d59c..096d9cbc3 100644 --- a/doc/tut/medcoupling/test-paravis.py +++ b/doc/tut/medcoupling/test-paravis.py @@ -36,7 +36,7 @@ def createALocalMesh(): targetMesh.setName("MyMesh3D"); targetMesh.setDescription("build3DMesh"); targetMesh.allocateCells(12); - for i in xrange(8): + for i in range(8): targetMesh.insertNextCell(NORM_HEXA8,8,targetConn[8*i:8*(i+1)]); pass targetMesh.finishInsertingCells(); @@ -62,7 +62,7 @@ def createALocalField2(): field=MEDCouplingFieldDouble.New(ON_NODES,ONE_TIME) field.setMesh(m) da=DataArrayDouble.New() - da.setValues([float(3*i) for i in xrange(27)],27,1) + da.setValues([float(3*i) for i in range(27)],27,1) field.setArray(da) field.setName("vitooNode") field.setTime(4.7,9,14) @@ -73,7 +73,7 @@ def createALocalMultiField3(): m=createALocalMesh() nbOfFields=100 fs=nbOfFields*[None] - for i in xrange(nbOfFields): + for i in range(nbOfFields): fs[i]=MEDCouplingFieldDouble.New(ON_CELLS,ONE_TIME) fs[i].setMesh(m) da=DataArrayDouble.New() @@ -106,7 +106,7 @@ def createALocalField5(): field.setMesh(m) da=DataArrayDouble.New() field.setTime(14.5,0,0) - da.setValues([float(7*i) for i in xrange(24)],24,1) + da.setValues([float(7*i) for i in range(24)],24,1) field.setName("MeshOnCMesh"); field.setArray(da) return field; @@ -132,28 +132,28 @@ paraviz=naming_service.Resolve("/Containers/%s/FactoryServer/PARAVIS_inst_1"%(co meshCorba=MEDCouplingUMeshServant._this(createALocalMesh()) ior=orb.object_to_string(meshCorba) -print "mesh : ",ior +print("mesh : ",ior) f1=MEDCouplingFieldDoubleServant._this(createALocalField1()) ior2=orb.object_to_string(f1) -print "Field on cell ",ior2 +print("Field on cell ",ior2) f2=MEDCouplingFieldDoubleServant._this(createALocalField2()) ior3=orb.object_to_string(f2) -print "Field on node ",ior3 +print("Field on node ",ior3) fs3=MEDCouplingFieldOverTimeServant._this(createALocalMultiField3()) fs3.Register() ior4=orb.object_to_string(fs3) -print "Fields over time ",ior4 +print("Fields over time ",ior4) m2=MEDCouplingCMeshServant._this(createALocalCMesh4()) ior5=orb.object_to_string(m2) -print "CMesh 2 : ",ior5 +print("CMesh 2 : ",ior5) f5=MEDCouplingFieldDoubleServant._this(createALocalField5()) ior6=orb.object_to_string(f5) -print "Field on cell CMesh ",ior6 +print("Field on cell CMesh ",ior6) script=""" src1 = ParaMEDCorbaPluginSource() diff --git a/doc/tut/medcoupling/testmed_gendata.py b/doc/tut/medcoupling/testmed_gendata.py index e99b7d2f3..1e0d480e4 100755 --- a/doc/tut/medcoupling/testmed_gendata.py +++ b/doc/tut/medcoupling/testmed_gendata.py @@ -42,7 +42,7 @@ def createGridMesh(meshName, nbCellsX, nbCellsY): cartesian mesh as a grid with nbCellsX segments in the X direction and nbCellsY in the Y direction (nb. cells = nbCellsX * nbCellsY) """ - print "Creating grid mesh of size %sx%s"%(nbCellsX, nbCellsY) + print("Creating grid mesh of size %sx%s"%(nbCellsX, nbCellsY)) cmesh=MC.MEDCouplingCMesh.New(); # Create X coordinates @@ -70,7 +70,7 @@ def unstructuredMesh(cartesianMesh): Convert the cartesian mesh in unstructured mesh for the need of write function of MEDLoader """ - print "Creating unstructured mesh from %s"%(cartesianMesh.getName()) + print("Creating unstructured mesh from %s"%(cartesianMesh.getName())) umesh=cartesianMesh.buildUnstructured(); umesh.setName(cartesianMesh.getName()) return umesh @@ -120,7 +120,7 @@ def createField(fieldName,gridMesh, nodes. In any case, it must be consistent with the dimensions of the numpy 2D array. """ - print "Creating field %s with iteration=%s"%(fieldName,iteration) + print("Creating field %s with iteration=%s"%(fieldName,iteration)) # The sizes are deduced from the numpy array. Note that if # typeOfField is ON_CELLS, then the size should correspond to the @@ -207,7 +207,7 @@ def createTestFieldOnNodes(): # A function can be a simple python function ... def f1(x,y): z = 10*x - print "x=%s\ny=%s\nz=%s"%(x,y,z) + print("x=%s\ny=%s\nz=%s"%(x,y,z)) return z # ... but also a more sophisticated callable object, for example to @@ -220,7 +220,7 @@ class Function(object): def function(self, x,y): z = self.param*x - print "x=%s\ny=%s\nz=%s"%(x,y,z) + print("x=%s\ny=%s\nz=%s"%(x,y,z)) return z def __call__(self, x,y): diff --git a/doc/tut/medcoupling/testmed_lena.py b/doc/tut/medcoupling/testmed_lena.py index 15558f587..5b5e68610 100755 --- a/doc/tut/medcoupling/testmed_lena.py +++ b/doc/tut/medcoupling/testmed_lena.py @@ -45,10 +45,10 @@ image = pilutil.imread("images/avatar.png",True) #im=Image.open("images/lena.png") #image=pilutil.fromimage(im,True) #image=numpy.asarray(im) -#print image +# print(image) dim = len(image.shape) -print "Image space dimension = %d"%dim +print("Image space dimension = %d"%dim) sizeX = image.shape[1] sizeY = image.shape[0] @@ -60,7 +60,7 @@ sizeY = image.shape[0] # double as required by the MEDCoupling field specification. import numpy imageDataNArray = image.reshape(1,sizeX*sizeY)[0] -print imageDataNArray +print(imageDataNArray) imageDataNArrayDouble = numpy.array(imageDataNArray, dtype='float64') imageDataArrayDouble = list(imageDataNArrayDouble) @@ -95,7 +95,7 @@ coordsY=MC.DataArrayDouble.New() coordsY.setValues(arrY,nbNodesY,1) cmesh.setCoords(coordsX,coordsY) -print "Imagem mesh dimension: %d"%cmesh.getSpaceDimension() +print("Imagem mesh dimension: %d"%cmesh.getSpaceDimension()) # WARN: In the current state of development of MEDLoader, only # unstructured meshes are supported for writting function in med diff --git a/doc/tut/medcoupling/testmed_simple.py b/doc/tut/medcoupling/testmed_simple.py index d14e18937..fa3f79d5f 100755 --- a/doc/tut/medcoupling/testmed_simple.py +++ b/doc/tut/medcoupling/testmed_simple.py @@ -53,7 +53,7 @@ sizeX = size nbNodesX = sizeX+1 stepX = 0.1 arrX = [float(i * stepX) for i in range(nbNodesX)] -print "Size of arrX = %d"%len(arrX) +print("Size of arrX = %d"%len(arrX)) coordsX=MC.DataArrayDouble.New() coordsX.setValues(arrX,nbNodesX,1) @@ -66,8 +66,8 @@ coordsY=MC.DataArrayDouble.New() coordsY.setValues(arrY,sizeY,1) cmesh.setCoords(coordsX,coordsY) -print cmesh.getSpaceDimension() -#print cmesh +print(cmesh.getSpaceDimension()) +# print(cmesh) # WARN: In the current state of development of MEDLoader, only # unstructured meshes are supported for writting function in med diff --git a/doc/tut/medcoupling/testpil.py b/doc/tut/medcoupling/testpil.py index 0f8ef702e..93f42c1ec 100755 --- a/doc/tut/medcoupling/testpil.py +++ b/doc/tut/medcoupling/testpil.py @@ -43,20 +43,20 @@ def image2matrix(): # Get the data imgdata=imgbw.getdata() width,height=imgbw.size - print list(imgdata) - print width,height + print(list(imgdata)) + print(width,height) # Convert the data in a matrix using numpy tab=numpy.array(imgdata,dtype='float64') - print list(tab) - print tab + print(list(tab)) + print(tab) nbRows=height nbCols=width matrix=numpy.reshape(tab,(nbRows,nbCols)) # Note that in the reshape function, the height (sizeY) of the image # is specified first, because it corresponds to the number of rows. - print matrix - print list(matrix) + print(matrix) + print(list(matrix)) import MEDCoupling as MC import MEDLoader as ML @@ -93,7 +93,7 @@ def createMesh(meshname, sizeX, sizeY): coordsY.setValues(arrY,nbNodesY,1) cmesh.setCoords(coordsX,coordsY) - print "Imagem mesh dimension: %d"%cmesh.getSpaceDimension() + print("Imagem mesh dimension: %d"%cmesh.getSpaceDimension()) # WARN: In the current state of development of MEDLoader, only # unstructured meshes are supported for writting function in med diff --git a/doc/tut/medloader/cmesh.py b/doc/tut/medloader/cmesh.py index eb688b1d0..447176ba0 100644 --- a/doc/tut/medloader/cmesh.py +++ b/doc/tut/medloader/cmesh.py @@ -32,7 +32,7 @@ itOrder=0 # Load as an unstructured mesh meshDimRelToMax = 0 # 0 = no restriction umesh = MEDLoader.ReadUMeshFromFile(filepath,meshName,meshDimRelToMax) -print "umesh is structured: %s"%umesh.isStructured() +print("umesh is structured: %s"%umesh.isStructured()) # Load as a structured mesh explicitly # _T2A @@ -41,17 +41,17 @@ medfile = MEDFileCMesh.New(filepath,meshName) cmesh = medfile.getMesh() # Note that the getMesh method is a short way to the method: #cmesh = medfile.getGenMeshAtLevel(0,False) -print "cmesh is structured: %s"%cmesh.isStructured() +print("cmesh is structured: %s"%cmesh.isStructured()) # _T2B # Load and let MEDLoader decide what is nature of the mesh # _T1A from MEDLoader import MEDFileMesh medfile = MEDFileMesh.New(filepath,meshName) -print medfile.advancedRepr() +print(medfile.advancedRepr()) meshDimRelToMax = 0 # 0 = no restriction mesh = medfile.getGenMeshAtLevel(meshDimRelToMax) -print "mesh is structured: %s"%mesh.isStructured() +print("mesh is structured: %s"%mesh.isStructured()) # _T1B @@ -65,7 +65,7 @@ medfile.write(outputfilepath,mode) # test to reload the mesh medfile = MEDFileCMesh.New(outputfilepath,meshName) cmesh = medfile.getMesh() -print "cmesh is structured: %s"%cmesh.isStructured() +print("cmesh is structured: %s"%cmesh.isStructured()) # Q: Is it possible to know if a mesh is structured or unstructured # without loading the mesh. diff --git a/doc/tut/medloader/explore.py b/doc/tut/medloader/explore.py index a045621d6..7241c1a1a 100644 --- a/doc/tut/medloader/explore.py +++ b/doc/tut/medloader/explore.py @@ -34,7 +34,7 @@ READ_PHYSICAL_DATA=False for meshName in meshNames: - print "%s"%meshName + print("%s"%meshName) # At this step, one can load the mesh of name meshName (but it is # not an obligation to continue to explore the metadata) @@ -53,7 +53,7 @@ for meshName in meshNames: for fieldName in fieldNames: - print " %s"%fieldName + print(" %s"%fieldName) # A field name could identify several MEDCoupling fields, that # differ by their spatial discretization on the mesh (values on @@ -71,7 +71,7 @@ for meshName in meshNames: listOfTypes = MEDLoader.GetTypesOfField(filepath,meshName,fieldName) for typeOfDiscretization in listOfTypes: - print " %s"%typeOfDiscretization + print(" %s"%typeOfDiscretization) # Then, we can get the iterations associated to this field on # this type of spatial discretization: @@ -85,7 +85,7 @@ for meshName in meshNames: for fieldIteration in fieldIterations: itNumber = fieldIteration[0] itOrder = fieldIteration[1] - print " (%s,%s)"%(itNumber,itOrder) + print(" (%s,%s)"%(itNumber,itOrder)) if READ_PHYSICAL_DATA: medCouplingField = MEDLoader.ReadField(typeOfDiscretization, @@ -95,4 +95,4 @@ for meshName in meshNames: fieldName, itNumber, itOrder) - print medCouplingField + print(medCouplingField) diff --git a/doc/tut/medloader/manage.py b/doc/tut/medloader/manage.py index cabbb820c..b163ba042 100644 --- a/doc/tut/medloader/manage.py +++ b/doc/tut/medloader/manage.py @@ -78,17 +78,17 @@ for meshName in meshNames: # request all the fields for a given iteration step, then we should # use the iteration step as a first classifaction switch of the tree -print fieldTree.keys() +print(list(fieldTree.keys())) # _T3A -for meshName in fieldTree.keys(): - print "%s"%meshName - for fieldName in fieldTree[meshName].keys(): - print " %s"%fieldName - for fieldType in fieldTree[meshName][fieldName].keys(): - print " %s"%fieldType - for itNumber in fieldTree[meshName][fieldName][fieldType].keys(): - for itOrder in fieldTree[meshName][fieldName][fieldType][itNumber].keys(): - print " (%s,%s)"%(itNumber,itOrder) - print fieldTree[meshName][fieldName][fieldType][itNumber][itOrder] +for meshName in list(fieldTree.keys()): + print("%s"%meshName) + for fieldName in list(fieldTree[meshName].keys()): + print(" %s"%fieldName) + for fieldType in list(fieldTree[meshName][fieldName].keys()): + print(" %s"%fieldType) + for itNumber in list(fieldTree[meshName][fieldName][fieldType].keys()): + for itOrder in list(fieldTree[meshName][fieldName][fieldType][itNumber].keys()): + print(" (%s,%s)"%(itNumber,itOrder)) + print(fieldTree[meshName][fieldName][fieldType][itNumber][itOrder]) # _T3B diff --git a/doc/tut/medloader/testamel.py b/doc/tut/medloader/testamel.py index ef18324e3..686b9eabb 100644 --- a/doc/tut/medloader/testamel.py +++ b/doc/tut/medloader/testamel.py @@ -65,4 +65,4 @@ fieldOnNodes.setMesh(msource) x=0.5 y=0.5 fieldValue = fieldOnNodes.getValueOn([x,y]) -print fieldValue +print(fieldValue) diff --git a/src/MEDCalc/cmp/MEDPresentation.cxx b/src/MEDCalc/cmp/MEDPresentation.cxx index 5c2ac3b9c..91fb7e781 100644 --- a/src/MEDCalc/cmp/MEDPresentation.cxx +++ b/src/MEDCalc/cmp/MEDPresentation.cxx @@ -29,6 +29,14 @@ #include +#if PY_VERSION_HEX < 0x03050000 +static char* +Py_EncodeLocale(const wchar_t *text, size_t *error_pos) +{ + return _Py_wchar2char(text, error_pos); +} +#endif + const std::string MEDPresentation::PROP_NAME = "name"; const std::string MEDPresentation::PROP_NB_COMPONENTS = "nbComponents"; const std::string MEDPresentation::PROP_SELECTED_COMPONENT = "selectedComponent"; @@ -580,8 +588,8 @@ MEDPresentation::fillAvailableFieldComponents() execPyLine(oss.str()); PyObject* p_obj = getPythonObjectFromMain("__nbCompo"); long nbCompo; - if (p_obj && PyInt_Check(p_obj)) - nbCompo = PyInt_AS_LONG(p_obj); + if (p_obj && PyLong_Check(p_obj)) + nbCompo = PyLong_AS_LONG(p_obj); else { STDLOG("Unexpected Python error"); @@ -595,8 +603,8 @@ MEDPresentation::fillAvailableFieldComponents() execPyLine(oss2.str()); PyObject* p_obj = getPythonObjectFromMain("__compo"); std::string compo; - if (p_obj && PyString_Check(p_obj)) - compo = std::string(PyString_AsString(p_obj)); // pointing to internal Python memory, so make a copy!! + if (p_obj && PyUnicode_Check(p_obj)) + compo = std::string(Py_EncodeLocale(PyUnicode_AS_UNICODE(p_obj), NULL)); // pointing to internal Python memory, so make a copy!! else { STDLOG("Unexpected Python error"); diff --git a/src/MEDCalc/cmp/test_medcalc_components.py b/src/MEDCalc/cmp/test_medcalc_components.py index 246c246a6..2bb8204c2 100644 --- a/src/MEDCalc/cmp/test_medcalc_components.py +++ b/src/MEDCalc/cmp/test_medcalc_components.py @@ -76,7 +76,7 @@ import os try: MED_ROOT_DIR=os.environ["MED_ROOT_DIR"] -except KeyError, e: +except KeyError as e: raise RuntimeError("MED_ROOT_DIR should be defined to load the test data") RESDIR=os.path.join(MED_ROOT_DIR,"share","salome","resources","med","medcalc_testfiles") @@ -114,7 +114,7 @@ def TEST_loadDatasource(): dataManager = factory.getDataManager() datasource = dataManager.loadDatasource(testFilePath) if datasource.name != testFileName: - print "ERR: datasource.name=%s (should be %s)"%(datasource.name,testFilePath) + print("ERR: datasource.name=%s (should be %s)"%(datasource.name,testFilePath)) return False # We try to load the file twice. It should not load twice and @@ -122,7 +122,7 @@ def TEST_loadDatasource(): sourceid_ref = datasource.id datasource = dataManager.loadDatasource(testFilePath) if datasource.id != sourceid_ref: - print "ERR: datasource.id=%s (should be %s)"%(datasource.id,sourceid_ref) + print("ERR: datasource.id=%s (should be %s)"%(datasource.id,sourceid_ref)) return False return True @@ -141,7 +141,7 @@ def TEST_getFieldRepresentation(): fieldHandlerList = dataManager.getFieldHandlerList() fieldHandler0 = fieldHandlerList[0] - print dataManager.getFieldRepresentation(fieldHandler0.id) + print(dataManager.getFieldRepresentation(fieldHandler0.id)) return True def TEST_updateFieldMetadata(): @@ -159,10 +159,10 @@ def TEST_updateFieldMetadata(): fieldHandler0.source) fieldHandlerModified = dataManager.getFieldHandler(fieldid) - print fieldHandlerModified + print(fieldHandlerModified) if fieldHandlerModified.fieldname != newname: - print "ERR: the name is %s (should be %s)"%(fieldHandlerModified.fieldname,newname) + print("ERR: the name is %s (should be %s)"%(fieldHandlerModified.fieldname,newname)) return False return True @@ -174,15 +174,15 @@ def TEST_saveFields(): fieldIdList = [fieldHandler0.id] filepath = "/tmp/test_xmed_saveFields.med" - print "fieldIdList = %s"%fieldIdList - print "filepath = %s"%filepath + print("fieldIdList = %s"%fieldIdList) + print("filepath = %s"%filepath) dataManager.saveFields(filepath,fieldIdList) # We just control that the file exists. But we should reload the # contents to check the fields import os if not os.path.exists(filepath): - print "ERR: the file %s does not exist"%(filepath) + print("ERR: the file %s does not exist"%(filepath)) return False return True @@ -195,7 +195,7 @@ def TEST_MEDDataManager_getMeshList(): dataManager = factory.getDataManager() datasourceHandler = dataManager.loadDatasource(testFilePath) meshHandlerList = dataManager.getMeshList(datasourceHandler.id) - print meshHandlerList + print(meshHandlerList) if len(meshHandlerList) == 0: return False @@ -208,7 +208,7 @@ def TEST_MEDDataManager_getMesh(): for mRef in meshHandlerList: meshId = mRef.id mRes = dataManager.getMesh(meshId) - print mRes + print(mRes) if ( mRes.name != mRef.name ) or ( mRes.sourceid != mRef.sourceid): return False return True @@ -221,7 +221,7 @@ def TEST_MEDDataManager_getFieldseriesListOnMesh(): # We look for the fieldseries defined on the first mesh of the list meshId = meshHandlerList[0].id fieldseriesList = dataManager.getFieldseriesListOnMesh(meshId) - print fieldseriesList + print(fieldseriesList) if len(fieldseriesList) == 0: return False @@ -242,7 +242,7 @@ def TEST_MEDDataManager_getFieldListInFieldseries(): # i.e. the time steps for this field. fieldseriesId = fieldseriesList[0].id fieldList = dataManager.getFieldListInFieldseries(fieldseriesId) - print fieldList + print(fieldList) if len(fieldList) == 0: return False @@ -261,22 +261,22 @@ def TEST_Calculator_basics(): # Try to operate on the two first fields fieldHandler0 = fieldHandlerList[0] fieldHandler1 = fieldHandlerList[1] - print fieldHandler0 - print fieldHandler1 + print(fieldHandler0) + print(fieldHandler1) calculator = factory.getCalculator() add = calculator.add(fieldHandler0, fieldHandler1) - print add + print(add) sub = calculator.sub(fieldHandler0, fieldHandler1) - print sub + print(sub) mul = calculator.mul(fieldHandler0, fieldHandler1) - print mul + print(mul) div = calculator.div(fieldHandler0, fieldHandler1) - print div + print(div) #power = calculator.pow(fieldHandler0, 2) - #print power + # print(power) linear = calculator.lin(fieldHandler0, 3,2) - print linear + print(linear) return True @@ -291,12 +291,12 @@ def TEST_Calculator_applyFunc(): import MEDCALC nbResultingComponent = MEDCALC.NBCOMP_DEFAULT res = calculator.fct(fieldHandler,"abs(u)",nbResultingComponent); - print res + print(res) # In this example, "a" stands for the first component nbResultingComponent = 1 res = calculator.fct(fieldHandler,"a+2",nbResultingComponent) - print res + print(res) return True @@ -320,7 +320,7 @@ def TEST_markAsPersistent(): dataManager.savePersistentFields(filepath) import os if not os.path.exists(filepath): - print "ERR: the file %s does not exist"%(filepath) + print("ERR: the file %s does not exist"%(filepath)) return False return True diff --git a/src/MEDCalc/exe/image2med/image2med.py b/src/MEDCalc/exe/image2med/image2med.py index 66eae7b64..defd7c8f1 100755 --- a/src/MEDCalc/exe/image2med/image2med.py +++ b/src/MEDCalc/exe/image2med/image2med.py @@ -30,11 +30,11 @@ parser.add_option("-m", "--medfile", dest="medfile", default=None, import sys, os if options.imagefile is None: - print "The image file must be specified" + print("The image file must be specified") sys.exit() imagefile = options.imagefile if not os.path.exists(imagefile): - print "The image file %s does not exists"%imagefile + print("The image file %s does not exists"%imagefile) sys.exit() if options.medfile is None: @@ -43,7 +43,7 @@ if options.medfile is None: else: medfile = options.medfile -print "Convert image file %s to a med field saved in %s"%(imagefile,medfile) +print("Convert image file %s to a med field saved in %s"%(imagefile,medfile)) from xmedimages import FieldBuilder builder = FieldBuilder() builder.image2med(imagefile,medfile) diff --git a/src/MEDCalc/gui/MEDEventListener_i.hxx b/src/MEDCalc/gui/MEDEventListener_i.hxx index 69da48647..2319c4ca4 100644 --- a/src/MEDCalc/gui/MEDEventListener_i.hxx +++ b/src/MEDCalc/gui/MEDEventListener_i.hxx @@ -22,6 +22,7 @@ #ifndef _MED_EVENTLISTENER_I_HXX_ #define _MED_EVENTLISTENER_I_HXX_ +#include #include #include CORBA_SERVER_HEADER(MEDEventListener) #include "SALOME_GenericObj_i.hh" diff --git a/src/MEDCalc/gui/MEDModule.hxx b/src/MEDCalc/gui/MEDModule.hxx index 7d7fab55f..9cbfc070c 100644 --- a/src/MEDCalc/gui/MEDModule.hxx +++ b/src/MEDCalc/gui/MEDModule.hxx @@ -22,6 +22,7 @@ #ifndef _MED_MODULE_HXX_ #define _MED_MODULE_HXX_ +#include #include "MEDCALCGUI.hxx" #include diff --git a/src/MEDCalc/gui/MEDWidgetHelper.hxx b/src/MEDCalc/gui/MEDWidgetHelper.hxx index a5f60a561..4f1bceab1 100644 --- a/src/MEDCalc/gui/MEDWidgetHelper.hxx +++ b/src/MEDCalc/gui/MEDWidgetHelper.hxx @@ -20,6 +20,7 @@ #ifndef SRC_MEDCALC_GUI_MEDWIDGETHELPER_HXX_ #define SRC_MEDCALC_GUI_MEDWIDGETHELPER_HXX_ +#include #include "WidgetPresentationParameters.hxx" #include "PresentationEvent.hxx" diff --git a/src/MEDCalc/gui/PresentationController.hxx b/src/MEDCalc/gui/PresentationController.hxx index 7faa1a4dc..dcc16516c 100644 --- a/src/MEDCalc/gui/PresentationController.hxx +++ b/src/MEDCalc/gui/PresentationController.hxx @@ -20,10 +20,11 @@ #ifndef PRESENTATION_CONTROLLER_HXX #define PRESENTATION_CONTROLLER_HXX +#include "MEDEventListener_i.hxx" + #include #include "MEDCALCGUI.hxx" -#include "MEDEventListener_i.hxx" #include #include CORBA_SERVER_HEADER(MEDPresentationManager) #include CORBA_CLIENT_HEADER(MEDDataManager) diff --git a/src/MEDCalc/gui/ProcessingController.hxx b/src/MEDCalc/gui/ProcessingController.hxx index 0683e1696..67ce7ab14 100644 --- a/src/MEDCalc/gui/ProcessingController.hxx +++ b/src/MEDCalc/gui/ProcessingController.hxx @@ -20,6 +20,7 @@ #ifndef PROCESSING_CONTROLLER_HXX #define PROCESSING_CONTROLLER_HXX +#include #include "MEDCALCGUI.hxx" #include "MEDEventListener_i.hxx" diff --git a/src/MEDCalc/gui/WorkspaceController.cxx b/src/MEDCalc/gui/WorkspaceController.cxx index 5560882af..3124a12af 100644 --- a/src/MEDCalc/gui/WorkspaceController.cxx +++ b/src/MEDCalc/gui/WorkspaceController.cxx @@ -469,7 +469,7 @@ void WorkspaceController::_exportItemList(QStringList itemNameIdList) { .arg(fieldHandler->type) .arg(fieldHandler->iteration); */ - commands += "print 'Not implemented yet'"; + commands += "print('Not implemented yet')"; _consoleDriver->exec(commands); } @@ -508,7 +508,7 @@ void WorkspaceController::_viewItemList(QStringList itemNameIdList) { // generate the scalar map on this field. QStringList commands; //commands+=QString("view(accessField(%1))").arg(fieldHandler->id); - commands += "print 'Not implemented yet'"; + commands += "print('Not implemented yet')"; _consoleDriver->exec(commands); } diff --git a/src/MEDCalc/gui/WorkspaceController.hxx b/src/MEDCalc/gui/WorkspaceController.hxx index c5fac88ad..ea73983cb 100644 --- a/src/MEDCalc/gui/WorkspaceController.hxx +++ b/src/MEDCalc/gui/WorkspaceController.hxx @@ -22,8 +22,8 @@ #ifndef _WORKSPACE_CONTROLLER_HXX #define _WORKSPACE_CONTROLLER_HXX -#include "TreeGuiManager.hxx" #include "MEDEventListener_i.hxx" +#include "TreeGuiManager.hxx" #include "XmedConsoleDriver.hxx" #include "DatasourceController.hxx" #include "PresentationController.hxx" diff --git a/src/MEDCalc/gui/XmedConsoleDriver.cxx b/src/MEDCalc/gui/XmedConsoleDriver.cxx index 0d4c4ae2f..631bd1811 100644 --- a/src/MEDCalc/gui/XmedConsoleDriver.cxx +++ b/src/MEDCalc/gui/XmedConsoleDriver.cxx @@ -18,9 +18,9 @@ // // Author : Guillaume Boulant (EDF) +#include "MEDModule.hxx" #include "XmedConsoleDriver.hxx" #include "Utils_SALOME_Exception.hxx" -#include "MEDModule.hxx" #include "MEDCommandsHistoryManager_i.hxx" #include "MEDFactoryClient.hxx" #include CORBA_CLIENT_HEADER(MED_Gen) diff --git a/src/MEDCalc/test/gui/test_qttesting.py b/src/MEDCalc/test/gui/test_qttesting.py index b5d421425..850663c1e 100644 --- a/src/MEDCalc/test/gui/test_qttesting.py +++ b/src/MEDCalc/test/gui/test_qttesting.py @@ -64,7 +64,7 @@ class MEDGUITest(unittest.TestCase): base_pth = os.path.join(GetBaselineDirGUI(), basename) gen_path = os.path.join(self._tmpDir, basename) - print base_pth, gen_path + print(base_pth, gen_path) try: ret = filecmp.cmp(base_pth, gen_path, shallow=False) except OSError: diff --git a/src/MEDCalc/test/tui/contour.py b/src/MEDCalc/test/tui/contour.py index b4643fe28..54e95eac9 100644 --- a/src/MEDCalc/test/tui/contour.py +++ b/src/MEDCalc/test/tui/contour.py @@ -41,5 +41,5 @@ try: presentation_id = medcalc.MakeContour(accessField(55), MEDCALC.VIEW_MODE_REPLACE, colorMap=MEDCALC.COLOR_MAP_BLUE_TO_RED_RAINBOW) sys.exit(-1); except: - print "Contour failed as expected." + print("Contour failed as expected.") sleep(1) diff --git a/src/MEDCalc/tui/__init__.py b/src/MEDCalc/tui/__init__.py index 149d37762..471500800 100644 --- a/src/MEDCalc/tui/__init__.py +++ b/src/MEDCalc/tui/__init__.py @@ -20,61 +20,61 @@ # This functions are to be used to notify the USER of some events # arising on the field operation. It is NOT to be used for logging # purpose -def inf(msg): print "INF: "+str(msg) -def wrn(msg): print "WRN: "+str(msg) -def err(msg): print "ERR: "+str(msg) -def dbg(msg): print "DBG: "+str(msg) +def inf(msg): print("INF: "+str(msg)) +def wrn(msg): print("WRN: "+str(msg)) +def err(msg): print("ERR: "+str(msg)) +def dbg(msg): print("DBG: "+str(msg)) # Initialize CORBA stuff -import medcorba +from . import medcorba # Connect event listener -import medevents +from . import medevents # Fields utilities -from fieldproxy import newFieldProxy, FieldProxy +from .fieldproxy import newFieldProxy, FieldProxy # Input/Output -from medio import LoadDataSource -from medio import LoadImageAsDataSource -from medio import GetFirstMeshFromDataSource -from medio import GetFirstFieldFromMesh +from .medio import LoadDataSource +from .medio import LoadImageAsDataSource +from .medio import GetFirstMeshFromDataSource +from .medio import GetFirstFieldFromMesh # Presentations -from medpresentation import MakeMeshView -from medpresentation import MakeScalarMap -from medpresentation import MakeContour -from medpresentation import MakeVectorField -from medpresentation import MakeSlices -from medpresentation import MakePointSprite -from medpresentation import RemovePresentation -from medpresentation import MakeDeflectionShape +from .medpresentation import MakeMeshView +from .medpresentation import MakeScalarMap +from .medpresentation import MakeContour +from .medpresentation import MakeVectorField +from .medpresentation import MakeSlices +from .medpresentation import MakePointSprite +from .medpresentation import RemovePresentation +from .medpresentation import MakeDeflectionShape -from medpresentation import GetMeshViewParameters -from medpresentation import GetScalarMapParameters -from medpresentation import GetContourParameters -from medpresentation import GetSlicesParameters -from medpresentation import GetPointSpriteParameters -from medpresentation import GetVectorFieldParameters -from medpresentation import GetDeflectionShapeParameters +from .medpresentation import GetMeshViewParameters +from .medpresentation import GetScalarMapParameters +from .medpresentation import GetContourParameters +from .medpresentation import GetSlicesParameters +from .medpresentation import GetPointSpriteParameters +from .medpresentation import GetVectorFieldParameters +from .medpresentation import GetDeflectionShapeParameters -from medpresentation import UpdateMeshView -from medpresentation import UpdateScalarMap -from medpresentation import UpdateContour -from medpresentation import UpdateSlices -from medpresentation import UpdateVectorField -from medpresentation import UpdatePointSprite -from medpresentation import UpdateDeflectionShape +from .medpresentation import UpdateMeshView +from .medpresentation import UpdateScalarMap +from .medpresentation import UpdateContour +from .medpresentation import UpdateSlices +from .medpresentation import UpdateVectorField +from .medpresentation import UpdatePointSprite +from .medpresentation import UpdateDeflectionShape -from medpresentation import ComputeCellAverageSize, GetDomainCenter, GetSliceOrigins, SelectSourceField +from .medpresentation import ComputeCellAverageSize, GetDomainCenter, GetSliceOrigins, SelectSourceField # Processing -from medprocessing import ChangeUnderlyingMesh -from medprocessing import InterpolateField +from .medprocessing import ChangeUnderlyingMesh +from .medprocessing import InterpolateField # Console commands -import medconsole +from . import medconsole # Playing test scenarii -from medtest import PlayQtTestingScenario -from medtest import RequestSALOMETermination +from .medtest import PlayQtTestingScenario +from .medtest import RequestSALOMETermination diff --git a/src/MEDCalc/tui/fieldproxy.py b/src/MEDCalc/tui/fieldproxy.py index ac80b13a0..d31b238c9 100644 --- a/src/MEDCalc/tui/fieldproxy.py +++ b/src/MEDCalc/tui/fieldproxy.py @@ -47,7 +47,7 @@ def _typeOfFieldLabel(typeOfField): # 3 = ON_GAUSS_NE try: return __mapTypeOfFieldLabel[typeOfField] - except IndexError, e: + except IndexError as e: return "UNKNOWN" # @@ -88,7 +88,7 @@ class FieldProxy: """ self.__fieldHandler = fieldHandler self.__restriction = None - print self.__repr__() + print(self.__repr__()) # def __getattr__(self, name ): """ @@ -105,7 +105,7 @@ class FieldProxy: handler. Only some attributes are writable. The list is specified in the PROXY_ATTRIBUTES_MAP table. """ - if name in PROXY_ATTRIBUTES_MAP.keys(): + if name in list(PROXY_ATTRIBUTES_MAP.keys()): if PROXY_ATTRIBUTES_MAP[name] is not None: medcalc.wrn("The modification of this attribute can't be done that way") msg="Use f.update(%s=\"%s\") instead to ensure synchronisation of data." @@ -135,7 +135,7 @@ class FieldProxy: # def __str__(self): """ - This is what is displayed when you type 'print myField'. Note + This is what is displayed when you type 'print(myField)'. Note that this function prints the values of the field and then you must be aware that a huge amount of data could be displayed. Moreover, it means that this operation triggers the @@ -170,7 +170,7 @@ class FieldProxy: offset = operande medcalc.inf("Application of the offset %s to %s" % (offset, self.fieldname)) rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -207,7 +207,7 @@ class FieldProxy: offset = -operande medcalc.inf("Application of the offset %s to %s" % (offset, self.fieldname)) rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -233,7 +233,7 @@ class FieldProxy: medcalc.inf("Linear transformation %s%s*%s" % (offset, factor, self.fieldname)) try: rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -257,7 +257,7 @@ class FieldProxy: offset = 0 medcalc.inf("Scaling %s by factor %s" % (self.fieldname, factor)) rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -288,7 +288,7 @@ class FieldProxy: offset = 0 medcalc.inf("Scaling %s by factor 1/%s" % (self.fieldname, operande)) rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -304,7 +304,7 @@ class FieldProxy: nbResComp = MEDCALC.NBCOMP_DEFAULT try: rfieldHandler = calculator.fct(self.__fieldHandler,function,nbResComp) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -337,7 +337,7 @@ class FieldProxy: medcalc.inf("Duplication of %s"%self.fieldname) try: rfieldHandler = calculator.dup(self.__fieldHandler) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -356,7 +356,7 @@ class FieldProxy: rfieldHandler = calculator.fct(self.__fieldHandler, function, MEDCALC.NBCOMP_DEFAULT) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) return None @@ -403,7 +403,7 @@ class FieldProxy: notifyGui_updateField(self.id) # Print for visual control - print self.__repr__() + print(self.__repr__()) # # @@ -414,8 +414,8 @@ class FieldProxy: # def TEST_typeOfFieldLabel(): - print typeOfFieldLabel(0) - print typeOfFieldLabel(5) + print(typeOfFieldLabel(0)) + print(typeOfFieldLabel(5)) # # =================================================================== diff --git a/src/MEDCalc/tui/medconsole.py b/src/MEDCalc/tui/medconsole.py index 4384b080e..0dbbde5a0 100644 --- a/src/MEDCalc/tui/medconsole.py +++ b/src/MEDCalc/tui/medconsole.py @@ -45,34 +45,34 @@ def saveWorkspace(filename): """ try: dataManager.savePersistentFields(filename) - except SALOME.SALOME_Exception, ex: + except SALOME.SALOME_Exception as ex: medcalc.err(ex.details.text) # # Clean workspace -from medevents import notifyGui_cleanWorkspace +from .medevents import notifyGui_cleanWorkspace def cleanWorkspace(): dvars = pyConsoleGlobals if dvars is None: return all_keys = [] - for varkey, var in dvars.items(): + for varkey, var in list(dvars.items()): if isinstance(var, medcalc.FieldProxy): all_keys.append("%s"%varkey) if len(all_keys) > 0: - exec "del "+",".join(all_keys) in pyConsoleGlobals + exec("del "+",".join(all_keys), pyConsoleGlobals) notifyGui_cleanWorkspace() # # Remove variable from console -from medevents import notifyGui_removeFromWorkspace +from .medevents import notifyGui_removeFromWorkspace def removeFromWorkspace(fieldProxy): dvars = pyConsoleGlobals if dvars is None: return - for varkey, var in dvars.items(): + for varkey, var in list(dvars.items()): if isinstance(var, medcalc.FieldProxy) and var.id == fieldProxy.id: - exec("del %s"%varkey) in pyConsoleGlobals + exec(("del %s"%varkey), pyConsoleGlobals) notifyGui_removeFromWorkspace(fieldProxy.id) # @@ -90,7 +90,7 @@ def getEnvironment(local=True, remote=False): medcalc.inf("Type this command \"import medcalc; medcalc.setConsoleGlobals(globals())") if remote is True: status="========= Fields used in the current context ===\n" - for varkey in dvars.keys(): + for varkey in list(dvars.keys()): var = dvars[varkey] if isinstance(var, medcalc.FieldProxy): status+="%s \t(id=%s, name=%s)\n"%(varkey,var.id,var.fieldname) @@ -116,7 +116,7 @@ def getEnvironment(local=True, remote=False): # # For simpler typing, one can create a python command for status -# (avoid to type "print getEnvironment()") +# (avoid to type "print(getEnvironment())") class ListFields(object): """ A stat object displays the status of the med operating context, i.e. the @@ -140,7 +140,7 @@ la = ListFields(all=True) # # Add variable to workspace -from medevents import notifyGui_putInWorkspace +from .medevents import notifyGui_putInWorkspace def putInWorkspace(fieldProxy): """ This function puts a reference to this field in the GUI data diff --git a/src/MEDCalc/tui/medevents.py b/src/MEDCalc/tui/medevents.py index 52be16a11..1d41ff7cf 100644 --- a/src/MEDCalc/tui/medevents.py +++ b/src/MEDCalc/tui/medevents.py @@ -36,16 +36,16 @@ def connectEventListener(): try: eventListenerIOR = dataManager.getEventListenerIOR() __eventListener = salome.orb.string_to_object(eventListenerIOR) - except SALOME.SALOME_Exception, e: + except SALOME.SALOME_Exception as e: medcalc.wrn("The event listener is not running yet") msg ="When you'll have loaded the MED GUI, " msg+="call explicitely \"medcalc.medevents.connectEventListener()\" " msg+="to connect the GUI event listener" medcalc.inf(msg) __eventListener = None - except Exception, e: + except Exception as e: medcalc.err("An unknown error occurs. Check if this ior=%s is valid."%eventListenerIOR) - print e + print(e) # def eventListenerIsRunning(): diff --git a/src/MEDCalc/tui/medimages.py b/src/MEDCalc/tui/medimages.py index 88b4c6d33..96a8892a2 100644 --- a/src/MEDCalc/tui/medimages.py +++ b/src/MEDCalc/tui/medimages.py @@ -83,7 +83,7 @@ class FieldBuilder: coordsY.setValues(arrY,nbNodesY,1) cmesh.setCoords(coordsX,coordsY) - print "Imagem mesh dimension: %d"%cmesh.getSpaceDimension() + print("Imagem mesh dimension: %d"%cmesh.getSpaceDimension()) # WARN: In the current state of development of MEDLoader, only # unstructured meshes are supported for writting function in med diff --git a/src/MEDCalc/tui/medio.py b/src/MEDCalc/tui/medio.py index df59c1ba5..d33b838da 100644 --- a/src/MEDCalc/tui/medio.py +++ b/src/MEDCalc/tui/medio.py @@ -34,7 +34,7 @@ def LoadImageAsDataSource(filename): medfilename = temp.name temp.close() - from medimages import FieldBuilder + from .medimages import FieldBuilder builder = FieldBuilder() builder.image2med(filename, medfilename) return LoadDataSource(medfilename) diff --git a/src/MEDCalc/tui/medpresentation.py b/src/MEDCalc/tui/medpresentation.py index 7c1d5f9b2..d93d85852 100644 --- a/src/MEDCalc/tui/medpresentation.py +++ b/src/MEDCalc/tui/medpresentation.py @@ -20,6 +20,7 @@ import medcalc import MEDCALC, SALOME from medcalc.medevents import notifyGui_addPresentation, notifyGui_removePresentation, notifyGui_error, notifyGui_modifyPresentation +from functools import reduce __manager = medcalc.medcorba.factory.getPresentationManager() @@ -149,7 +150,7 @@ def RemovePresentation(presentation_id): # def __GetGENERICParameters(tag, presentation_id): - exec "params = __manager.get%sParameters(presentation_id)" % tag + exec("params = __manager.get%sParameters(presentation_id)" % tag) return params GetMeshViewParameters = lambda pres_id: __GetGENERICParameters("MeshView", pres_id) @@ -162,7 +163,7 @@ GetDeflectionShapeParameters = lambda pres_id: __GetGENERICParameters("Deflectio def __UpdateGENERIC(tag, presentation_id, params): - exec "__manager.update%s(presentation_id, params)" % tag + exec("__manager.update%s(presentation_id, params)" % tag) notifyGui_modifyPresentation(presentation_id) UpdateMeshView = lambda pres_id, params: __UpdateGENERIC("MeshView", pres_id, params) @@ -178,7 +179,7 @@ def ComputeCellAverageSize(obj): @return the average cell size """ bb, nCells = obj.GetDataInformation().GetBounds(), obj.GetDataInformation().GetNumberOfCells() - bb = zip(bb[::2], bb[1::2]) + bb = list(zip(bb[::2], bb[1::2])) deltas = [x[1]-x[0] for x in bb] ## Filter out null dimensions: avgDelta = sum(deltas) / 3.0 @@ -193,7 +194,7 @@ def GetDomainCenter(obj): @return the center of the domain as the central point of the bounding box """ bb = obj.GetDataInformation().GetBounds() - bb = zip(bb[::2], bb[1::2]) + bb = list(zip(bb[::2], bb[1::2])) mids = [x[0] + 0.5*(x[1]-x[0]) for x in bb] return mids @@ -204,7 +205,7 @@ def GetSliceOrigins(obj, nbSlices, normal): """ from math import sqrt bb = obj.GetDataInformation().GetBounds() - bb = zip(bb[::2], bb[1::2]) + bb = list(zip(bb[::2], bb[1::2])) origin = [x[0] + 0.5*(x[1]-x[0]) for x in bb] deltas = [x[1]-x[0] for x in bb] # Compute extent of slices: diff --git a/src/MEDCalculator/Swig/MEDCalculator.i b/src/MEDCalculator/Swig/MEDCalculator.i index e6445f3e1..2a75aff0c 100644 --- a/src/MEDCalculator/Swig/MEDCalculator.i +++ b/src/MEDCalculator/Swig/MEDCalculator.i @@ -170,8 +170,7 @@ namespace MEDCoupling if(!PySlice_Check(obj)) throw INTERP_KERNEL::Exception(msg); Py_ssize_t strt,stp,step; - PySliceObject *oC=reinterpret_cast(obj); - PySlice_GetIndices(oC,std::numeric_limits::max(),&strt,&stp,&step); + PySlice_GetIndices(obj,std::numeric_limits::max(),&strt,&stp,&step); if(strt!=0 || stp!=std::numeric_limits::max() || step!=1) throw INTERP_KERNEL::Exception(msg); tr.setAll(); pr.setAll(); cr.setAll(); @@ -189,9 +188,9 @@ namespace MEDCoupling convertPyObjToRS2(obj2,cr,"for 3rd tuple element for components of field"); } MCAuto ret=self->operator()(tr,pr,cr); - if(PyInt_Check(val)) + if(PyLong_Check(val)) { - (*ret)=double(PyInt_AS_LONG(val)); + (*ret)=double(PyLong_AS_LONG(val)); ret->incrRef(); return ret; } diff --git a/src/MEDCalculator/Swig/MEDCalculatorBasicsTest.py b/src/MEDCalculator/Swig/MEDCalculatorBasicsTest.py index 783e4c433..0608d1a56 100644 --- a/src/MEDCalculator/Swig/MEDCalculatorBasicsTest.py +++ b/src/MEDCalculator/Swig/MEDCalculatorBasicsTest.py @@ -57,12 +57,12 @@ class MEDCalculatorBasicsTest(unittest.TestCase): Power=MEDCalculatorDBFieldReal(f) v=Power.getValues() self.assertEqual(10,len(v)); - for i in xrange(10): + for i in range(10): v1=v[i] self.assertEqual(35,len(v1)) l=0 - for j in xrange(5): - for k in xrange(7): + for j in range(5): + for k in range(7): self.assertAlmostEqual((i+1)*100.+(j+1)*10.+k+1,v1[l],12); l+=1 pass @@ -71,12 +71,12 @@ class MEDCalculatorBasicsTest(unittest.TestCase): p1=Power[2:4,:,:] v=p1.getValues() self.assertEqual(2,len(v)); - for i in xrange(2): + for i in range(2): v1=v[i] self.assertEqual(35,len(v1)) l=0 - for j in xrange(5): - for k in xrange(7): + for j in range(5): + for k in range(7): self.assertAlmostEqual((i+3)*100.+(j+1)*10.+k+1,v1[l],12); l+=1 pass @@ -85,12 +85,12 @@ class MEDCalculatorBasicsTest(unittest.TestCase): p2=Power[3:7,:,2:5] v=p2.getValues() self.assertEqual(4,len(v)); - for i in xrange(4): + for i in range(4): v1=v[i] self.assertEqual(15,len(v1)) l=0 - for j in xrange(5): - for k in xrange(3): + for j in range(5): + for k in range(3): self.assertAlmostEqual((i+4)*100.+(j+1)*10.+k+3,v1[l],12); l+=1 pass @@ -101,11 +101,11 @@ class MEDCalculatorBasicsTest(unittest.TestCase): v=p3.getValues() self.assertEqual(4,len(v)); expected=[[162192.0, 178952.0, 196112.0, 213672.0, 231632.0], [347792.0, 368552.0, 389712.0, 411272.0, 433232.0], [573392.0, 598152.0, 623312.0, 648872.0, 674832.0], [838992.0, 867752.0, 896912.0, 926472.0, 956432.0]] - for i in xrange(4): + for i in range(4): v1=v[i] self.assertEqual(5,len(v1)) l=0 - for j in xrange(5): + for j in range(5): self.assertAlmostEqual(expected[i][j],v1[l],8); l+=1 pass @@ -114,12 +114,12 @@ class MEDCalculatorBasicsTest(unittest.TestCase): Power[:,:,2:4]=7. v=Power.getValues() self.assertEqual(10,len(v)); - for i in xrange(10): + for i in range(10): v1=v[i] self.assertEqual(35,len(v1)) l=0 - for j in xrange(5): - for k in xrange(2): + for j in range(5): + for k in range(2): self.assertAlmostEqual((i+1)*100.+(j+1)*10.+k+1,v1[l],12); l+=1 pass @@ -127,7 +127,7 @@ class MEDCalculatorBasicsTest(unittest.TestCase): l+=1 self.assertAlmostEqual(7.,v1[l],12); l+=1 - for k in xrange(3): + for k in range(3): self.assertAlmostEqual((i+1)*100.+(j+1)*10.+k+5,v1[l],12); l+=1 pass @@ -136,12 +136,12 @@ class MEDCalculatorBasicsTest(unittest.TestCase): Power[1:5,:,3]=p3 v=Power[1:5,:,:].getValues() self.assertEqual(4,len(v)); - for i in xrange(4): + for i in range(4): v1=v[i] self.assertEqual(35,len(v1)) l=0 - for j in xrange(5): - for k in xrange(2): + for j in range(5): + for k in range(2): self.assertAlmostEqual((i+2)*100.+(j+1)*10.+k+1,v1[l],12); l+=1 pass @@ -149,7 +149,7 @@ class MEDCalculatorBasicsTest(unittest.TestCase): l+=1 self.assertAlmostEqual(expected[i][j],v1[l],8); l+=1 - for k in xrange(3): + for k in range(3): self.assertAlmostEqual((i+2)*100.+(j+1)*10.+k+5,v1[l],12); l+=1 pass diff --git a/src/MEDCalculator/Swig/MEDCalculatorTypemaps.i b/src/MEDCalculator/Swig/MEDCalculatorTypemaps.i index 9c89de80f..ebbd5a0f9 100644 --- a/src/MEDCalculator/Swig/MEDCalculatorTypemaps.i +++ b/src/MEDCalculator/Swig/MEDCalculatorTypemaps.i @@ -32,9 +32,9 @@ static PyObject* convertMEDCalculatorDBField(MEDCoupling::MEDCalculatorDBField * void convertPyObjToRS(PyObject *o, MEDCoupling::MEDCalculatorDBRangeSelection& rs) { - if(PyInt_Check(o)) + if(PyLong_Check(o)) { - int val=(int)PyInt_AS_LONG(o); + int val=(int)PyLong_AS_LONG(o); rs=val; return ; } @@ -49,9 +49,9 @@ void convertPyObjToRS(PyObject *o, MEDCoupling::MEDCalculatorDBRangeSelection& r void convertPyObjToRS2(PyObject *o, MEDCoupling::MEDCalculatorDBRangeSelection& rs, const char *msg) { - if(PyInt_Check(o)) + if(PyLong_Check(o)) { - int val=(int)PyInt_AS_LONG(o); + int val=(int)PyLong_AS_LONG(o); rs=val; return ; } @@ -62,8 +62,7 @@ void convertPyObjToRS2(PyObject *o, MEDCoupling::MEDCalculatorDBRangeSelection& throw INTERP_KERNEL::Exception(oss.str().c_str()); } Py_ssize_t strt,stp,step; - PySliceObject *oC=reinterpret_cast(o); - PySlice_GetIndices(oC,std::numeric_limits::max(),&strt,&stp,&step); + PySlice_GetIndices(o,std::numeric_limits::max(),&strt,&stp,&step); rs.setPyStart(strt); rs.setPyEnd(stp); } diff --git a/src/MEDCalculator/Swig/SPythonInterpreter.cxx b/src/MEDCalculator/Swig/SPythonInterpreter.cxx index 3c3de5adc..c73533399 100644 --- a/src/MEDCalculator/Swig/SPythonInterpreter.cxx +++ b/src/MEDCalculator/Swig/SPythonInterpreter.cxx @@ -193,12 +193,14 @@ bool SPythonInterpreter::isSPythonExpression(const std::string& s) return false; if(w.find("del ")!=std::string::npos) return false; - const char PRINT[]="print "; + const char PRINT[]="print("; + const char ENDPRINT[]=")"; bool isPrint=w.find(PRINT)!=std::string::npos; + isPrint &= w.find(ENDPRINT)!=std::string::npos; if(isPrint) { std::size_t p=w.find(PRINT); - w=w.substr(p+sizeof(PRINT)-1); + w=w.substr(p+sizeof(PRINT)-sizeof(ENDPRINT)-1); } std::string result; if(!isSPythonExpressionLev1(w,result)) diff --git a/src/MEDCalculator/Swig/SPythonParser.cxx b/src/MEDCalculator/Swig/SPythonParser.cxx index 39858b1fc..b69eb526d 100644 --- a/src/MEDCalculator/Swig/SPythonParser.cxx +++ b/src/MEDCalculator/Swig/SPythonParser.cxx @@ -31,6 +31,14 @@ const char SPythonPredParser::FIELD_TYPE_STR[]="MEDCalculatorDBField"; const char SPythonParser::NUMBERS[]="0123456789"; +#if PY_VERSION_HEX < 0x03050000 +static char* +Py_EncodeLocale(const wchar_t *text, size_t *error_pos) +{ + return _Py_wchar2char(text, error_pos); +} +#endif + SPythonParser::SPythonParser():_type(EMPTY_TYPE) { } @@ -451,7 +459,7 @@ TypeOfEntity SPythonPredParser::getTypeOfVar(const std::string& var, PyObject *g oss << TMPVAR << "=type(" << var << ").__name__"; PyRun_String(oss.str().c_str(),Py_single_input,glob,loc); PyObject *p=PyDict_GetItemString(glob,TMPVAR); - const char *type=PyString_AS_STRING(p); + const char *type=Py_EncodeLocale(PyUnicode_AS_UNICODE(p), NULL); std::string typecpp=std::string(type); if(typecpp=="function") return FUNC_TYPE; diff --git a/src/MEDCalculator/Swig/test.spy b/src/MEDCalculator/Swig/test.spy index a5110a0dc..e918307c9 100644 --- a/src/MEDCalculator/Swig/test.spy +++ b/src/MEDCalculator/Swig/test.spy @@ -23,4 +23,4 @@ def f(i): def f(i): return i+3 -print f(56.) +print(f(56.)) diff --git a/src/MEDCalculator/Swig/test2.spy b/src/MEDCalculator/Swig/test2.spy index e9d89ca65..51e2964fa 100644 --- a/src/MEDCalculator/Swig/test2.spy +++ b/src/MEDCalculator/Swig/test2.spy @@ -35,9 +35,9 @@ Power2=Power(1:3,:,2:)+(3+5) Power=0 Power3=Power2 3.6/Power3(0:2,:,2) -print 2+Power3(0:2,:,:)*4 +print(2+Power3(0:2,:,:)*4) Power4=Power3.magnitude() -print Power3.getValues() +print(Power3.getValues()) Power4.applyFunc("3*x") Power6=Power(0:2,:,1:4) Power7=Power(7:9,:,4:) diff --git a/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTest.py b/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTest.py index 57c976b6d..bc34a6837 100644 --- a/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTest.py +++ b/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTest.py @@ -78,7 +78,7 @@ class MEDCouplingCorbaServBasicsTest: targetMesh.setName("MyMesh3D"); targetMesh.setDescription("build3DMesh"); targetMesh.allocateCells(12); - for i in xrange(8): + for i in range(8): targetMesh.insertNextCell(NORM_HEXA8,8,targetConn[8*i:8*(i+1)]); pass targetMesh.finishInsertingCells(); @@ -353,7 +353,7 @@ class MEDCouplingCorbaServBasicsTest: f.setGaussLocalizationOnType(NORM_QUAD4,_refCoo2,_gsCoo1,_wg1); array=DataArrayDouble.New(); ptr=18*2*[None] - for i in xrange(18*2): + for i in range(18*2): ptr[i]=float(i+1); pass array.setValues(ptr,18,2); @@ -376,7 +376,7 @@ class MEDCouplingCorbaServBasicsTest: f.setDescription("MyDescriptionNE"); array=DataArrayDouble.New(); ptr=18*2*[None] - for i in xrange(18*2): + for i in range(18*2): ptr[i]=float(i+7) array.setValues(ptr,18,2); array.setInfoOnComponent(0,"Power [MW]"); diff --git a/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTestClt.py b/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTestClt.py index 5a40028d7..734885699 100644 --- a/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTestClt.py +++ b/src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTestClt.py @@ -29,11 +29,11 @@ f=file(MEDCouplingCorbaSwigTest.FileIOR1,"r") ior=f.read() f=MEDCouplingCorbaSwigTest.testField() fCorbaIOR=orb.string_to_object(ior) -print fCorbaIOR +print(fCorbaIOR) for i in range(50): fCpy=MEDCouplingFieldDoubleClient.New(fCorbaIOR) - print fCpy.isEqual(f,1e-12,1e-12) + print(fCpy.isEqual(f,1e-12,1e-12)) pass fCorbaIOR.UnRegister() @@ -43,7 +43,7 @@ m=MEDCouplingCorbaSwigTest.testMesh() mCorbaIOR=orb.string_to_object(ior) for i in range(50): mCpy=MEDCouplingUMeshClient.New(mCorbaIOR) - print mCpy.isEqual(m,1e-12) + print(mCpy.isEqual(m,1e-12)) pass mCorbaIOR.UnRegister() diff --git a/src/MEDCouplingCorba_Swig/TestMEDCouplingCorbaClt.py b/src/MEDCouplingCorba_Swig/TestMEDCouplingCorbaClt.py index 0aacae14d..861f23105 100644 --- a/src/MEDCouplingCorba_Swig/TestMEDCouplingCorbaClt.py +++ b/src/MEDCouplingCorba_Swig/TestMEDCouplingCorbaClt.py @@ -59,7 +59,7 @@ class MEDCouplingCorbaServBasicsTestClt(unittest.TestCase): pass def testMultiFetchingToTestMemoryManagement(self): - for i in xrange(1000): + for i in range(1000): meshPtr=self._objC.get2DMesh(); _mesh_from_distant=MEDCouplingUMeshClient.New(meshPtr); meshPtr.UnRegister(); @@ -198,14 +198,14 @@ class MEDCouplingCorbaServBasicsTestClt(unittest.TestCase): li=8*[None] th=8*[None] fieldPtr=self._objC.getFieldScalarOn2DNT(); - for i in xrange(8): + for i in range(8): th[i]=threading.Thread(None,self.corbaField2DNTMFMTThread,"Test"+str(i),(i,fieldPtr,li)) th[i].start() pass - for i in xrange(8): + for i in range(8): th[i].join() pass - for i in xrange(8-1): + for i in range(8-1): self.assertTrue(li[i].isEqual(li[i+1],1.e-12,1.e-15)); pass fieldPtr.UnRegister() @@ -418,7 +418,7 @@ class MEDCouplingCorbaServBasicsTestClt(unittest.TestCase): ts=fotc.getTimeSteps(); self.assertEqual(6,len(ts)); expected=[0.2,0.7,1.2,1.35,1.7,2.7]; - for i in xrange(6): + for i in range(6): self.assertAlmostEqual(expected[i],ts[i],12); pass -- 2.30.2