Salome HOME
Porting to Python 3 (1st draft)
authorGilles DAVID <gilles-g.david@edf.fr>
Thu, 30 Mar 2017 12:11:52 +0000 (14:11 +0200)
committerGilles DAVID <gilles-g.david@edf.fr>
Thu, 30 Mar 2017 12:11:52 +0000 (14:11 +0200)
43 files changed:
doc/tut/medcoupling/partition.py
doc/tut/medcoupling/pyfunctions/functions.py
doc/tut/medcoupling/pyfunctions/lagrange.py
doc/tut/medcoupling/pyfunctions/plotter.py
doc/tut/medcoupling/test-paravis.py
doc/tut/medcoupling/testmed_gendata.py
doc/tut/medcoupling/testmed_lena.py
doc/tut/medcoupling/testmed_simple.py
doc/tut/medcoupling/testpil.py
doc/tut/medloader/cmesh.py
doc/tut/medloader/explore.py
doc/tut/medloader/manage.py
doc/tut/medloader/testamel.py
src/MEDCalc/cmp/MEDPresentation.cxx
src/MEDCalc/cmp/test_medcalc_components.py
src/MEDCalc/exe/image2med/image2med.py
src/MEDCalc/gui/MEDEventListener_i.hxx
src/MEDCalc/gui/MEDModule.hxx
src/MEDCalc/gui/MEDWidgetHelper.hxx
src/MEDCalc/gui/PresentationController.hxx
src/MEDCalc/gui/ProcessingController.hxx
src/MEDCalc/gui/WorkspaceController.cxx
src/MEDCalc/gui/WorkspaceController.hxx
src/MEDCalc/gui/XmedConsoleDriver.cxx
src/MEDCalc/test/gui/test_qttesting.py
src/MEDCalc/test/tui/contour.py
src/MEDCalc/tui/__init__.py
src/MEDCalc/tui/fieldproxy.py
src/MEDCalc/tui/medconsole.py
src/MEDCalc/tui/medevents.py
src/MEDCalc/tui/medimages.py
src/MEDCalc/tui/medio.py
src/MEDCalc/tui/medpresentation.py
src/MEDCalculator/Swig/MEDCalculator.i
src/MEDCalculator/Swig/MEDCalculatorBasicsTest.py
src/MEDCalculator/Swig/MEDCalculatorTypemaps.i
src/MEDCalculator/Swig/SPythonInterpreter.cxx
src/MEDCalculator/Swig/SPythonParser.cxx
src/MEDCalculator/Swig/test.spy
src/MEDCalculator/Swig/test2.spy
src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTest.py
src/MEDCouplingCorba_Swig/MEDCouplingCorbaSwigTestClt.py
src/MEDCouplingCorba_Swig/TestMEDCouplingCorbaClt.py

index 4952cbc453b3146003341ccdc8ee7dd3d567a801..624000a47964319dc611bee0468f50b649397768 100644 (file)
@@ -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))
index 2ecb5c95ad68f9621ca797a8ec230fd6a6999ede..a39d0934c892f30bcc7ed2076c2cc3a25a884d48 100755 (executable)
@@ -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__":
index a98d159ba4bbd01b9ecfca516aedc8ebd0c81652..3913b1c0e920ddfccdafa122099f83b0b9181caf 100755 (executable)
@@ -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)
 
 
index e414655b1b3b3808037a5a8ea00f9b8d5863f448..7c52b758714b29598f4223335bea688711943206 100644 (file)
@@ -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()
index d0f59d59ca162a167e2c09eb909ba7ab2117bee7..096d9cbc3a267ff4c521d6ea612076b1a5010b41 100644 (file)
@@ -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()
index e99b7d2f37f605eef609809732ae6cc2ca8a6c71..1e0d480e404ace4c31c7efcee44b4e6a9683df67 100755 (executable)
@@ -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):
index 15558f5878873cf19ba0eb3802568650134aea54..5b5e686107a979d96e924850d185b7a6b7b8223f 100755 (executable)
@@ -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
index d14e18937ab7064295a0c1c242b7e9df7ca8f215..fa3f79d5f2ed39323d509d7cfba8b71fc8a760c7 100755 (executable)
@@ -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
index 0f8ef702ef97867b69606a4291fd76390259c45d..93f42c1ecaea543e100e2a85b494a498cd4948df 100755 (executable)
@@ -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
index eb688b1d055722d0590a4e6251864320e49e54a0..447176ba0b60eb2b7caaa68dc436797dadc8b973 100644 (file)
@@ -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.
index a045621d6703afd66d0c1d282e5f7f3a6fce679d..7241c1a1a47655cd4f50764010517a6199ae492a 100644 (file)
@@ -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)
index cabbb820c3fb6ea19d67f7bab89f7107d68129e0..b163ba0426cc5d235fa970ef4df53a10088cdd88 100644 (file)
@@ -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
index ef18324e34cb06a8869802f46c4753c0871aaf12..686b9eabbde31e8bfc07b9da26c7db93b6c19d67 100644 (file)
@@ -65,4 +65,4 @@ fieldOnNodes.setMesh(msource)
 x=0.5
 y=0.5
 fieldValue = fieldOnNodes.getValueOn([x,y])
-print fieldValue
+print(fieldValue)
index 5c2ac3b9caa28864e0ab6e52e7ee867121add6fd..91fb7e781fe92a03145be39da2582bf114641c19 100644 (file)
 
 #include <sstream>
 
+#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");
index 246c246a6644fe51b86b94904152e1ff6bc14f53..2bb8204c233a2db5520fccbc23295c420bb7bb8e 100644 (file)
@@ -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
 
index 66eae7b6447d55f0ce8baf6464f7f0db756bceb4..defd7c8f1d1cb913cc82f9a260b6d352647be89e 100755 (executable)
@@ -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)
index 69da48647706968c4de8cd3ccca6ca79c068b007..2319c4ca4cff736d110d40a520a73e22da66c8ce 100644 (file)
@@ -22,6 +22,7 @@
 #ifndef _MED_EVENTLISTENER_I_HXX_
 #define _MED_EVENTLISTENER_I_HXX_
 
+#include <Python.h>
 #include <SALOMEconfig.h>
 #include CORBA_SERVER_HEADER(MEDEventListener)
 #include "SALOME_GenericObj_i.hh"
index 7d7fab55ffe7a93d45f23964fd32fe0892d6541d..9cbfc070cec9909deabb0bc6ce23b03617529bbc 100644 (file)
@@ -22,6 +22,7 @@
 #ifndef _MED_MODULE_HXX_
 #define _MED_MODULE_HXX_
 
+#include <Python.h>
 #include "MEDCALCGUI.hxx"
 
 #include <SalomeApp_Module.h>
index a5f60a561897a0b73c087f2d90b15b1b26d58b8c..4f1bceab1ef03ce6e11041105c29cda9ffb331c8 100644 (file)
@@ -20,6 +20,7 @@
 #ifndef SRC_MEDCALC_GUI_MEDWIDGETHELPER_HXX_
 #define SRC_MEDCALC_GUI_MEDWIDGETHELPER_HXX_
 
+#include <Python.h>
 #include "WidgetPresentationParameters.hxx"
 #include "PresentationEvent.hxx"
 
index 7faa1a4dc2a922910bb9325691a37d0bc94aa04e..dcc16516c5a5ffd191804d94595251e57c690333 100644 (file)
 #ifndef PRESENTATION_CONTROLLER_HXX
 #define PRESENTATION_CONTROLLER_HXX
 
+#include "MEDEventListener_i.hxx"
+
 #include <QObject>
 #include "MEDCALCGUI.hxx"
 
-#include "MEDEventListener_i.hxx"
 #include <SALOMEconfig.h>
 #include CORBA_SERVER_HEADER(MEDPresentationManager)
 #include CORBA_CLIENT_HEADER(MEDDataManager)
index 0683e1696b449ba7de0340c108bdf68facac3f28..67ce7ab1482981095108d6eb9a3e4d4b229f764a 100644 (file)
@@ -20,6 +20,7 @@
 #ifndef PROCESSING_CONTROLLER_HXX
 #define PROCESSING_CONTROLLER_HXX
 
+#include <Python.h>
 #include "MEDCALCGUI.hxx"
 
 #include "MEDEventListener_i.hxx"
index 5560882af3630d0d3842d489850ecef198b1bc00..3124a12af1eafb8856be37e277e758a9a957818a 100644 (file)
@@ -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);
 }
 
index c5fac88adddfa536030293a95186c4902283f53e..ea73983cba304e3f55f21c0036a5c65ce3501f7d 100644 (file)
@@ -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"
index 0d4c4ae2f80b4a6e9e354210bbf4e7485e7c6abb..631bd1811290e33ea76483bc3b10144c7277bdd9 100644 (file)
@@ -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)
index b5d421425e7332dd1bea3bfaecbeec737aba352d..850663c1e2060e4276a1ce72e563c504666d6b1f 100644 (file)
@@ -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:
index b4643fe2879188d424324fad36351950d4676f5e..54e95eac97242db41299c0491c946c06e64ed989 100644 (file)
@@ -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)
index 149d377625fb6206e2c8e5ff1d3ec784a9e151d6..471500800baae22758c4ec58cbd3f5cf81f78b9a 100644 (file)
 # 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
index ac80b13a0066cc53c9cc016d9e67bed36bc7ef7d..d31b238c9939528a1c7bee343deae49e9bbde06d 100644 (file)
@@ -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))
 #
 
 # ===================================================================
index 4384b080e47b487d71fdd3d73432343cdf2372bd..0dbbde5a0ed3eebf87efdc7447bdac44d215f5a3 100644 (file)
@@ -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
index 52be16a11715b1a72967b1f347574600aa7d63df..1d41ff7cf8a283e8ac9e1d457a65431c8b6e4ea1 100644 (file)
@@ -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():
index 88b4c6d33879709b51c0c916d84f9b66f49a8b6f..96a8892a25d06748d0394b0d1fc736e55d403d39 100644 (file)
@@ -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
index df59c1ba5bd3552d5ff14b441d20b7ee034d9cb7..d33b838da1c98a3d178d386b13bec2daae92cd4e 100644 (file)
@@ -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)
index 7c1d5f9b2b35c95022f0d2e1fbf6534c94e8e2a7..d93d858529f9c76c94bbf08d86e043de8a70ec44 100644 (file)
@@ -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:
index e6445f3e1e22145e8d59bad2daac9466aa29b87d..2a75aff0c7729ec40033a67e62deb8c6292b069a 100644 (file)
@@ -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<PySliceObject *>(obj);
-               PySlice_GetIndices(oC,std::numeric_limits<int>::max(),&strt,&stp,&step);
+               PySlice_GetIndices(obj,std::numeric_limits<int>::max(),&strt,&stp,&step);
                if(strt!=0 || stp!=std::numeric_limits<int>::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<MEDCalculatorDBFieldReal> 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;
              }
index 783e4c4338994139f2c7d81ffad4b5545264c86b..0608d1a56302019f53760cb0c2f1a114c4b9c512 100644 (file)
@@ -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
index 9c89de80fd894773ed9021abc95c6ca1dd90d6a5..ebbd5a0f906b2c70959baf3a0ace41a5163c5de5 100644 (file)
@@ -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<PySliceObject *>(o);
-  PySlice_GetIndices(oC,std::numeric_limits<int>::max(),&strt,&stp,&step);
+  PySlice_GetIndices(o,std::numeric_limits<int>::max(),&strt,&stp,&step);
   rs.setPyStart(strt);
   rs.setPyEnd(stp);
 }
index 3c3de5adccd0a6bfae94642c070f76f57cdabd25..c73533399334b5c0cdda4b75bdb355bcf248ac5a 100644 (file)
@@ -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))
index 39858b1fc7058b3b07a6e4caac7200b9d108d7ed..b69eb526df57a421f6d0d9adf3ad48b173678c54 100644 (file)
@@ -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;
index a5110a0dc88632c3145d0ccb13bc8a1c7e06e6d4..e918307c90ddba90b98ff08c91bfab54b157ef30 100644 (file)
@@ -23,4 +23,4 @@ def f(i):
 def f(i):
     return i+3
 
-print f(56.)
+print(f(56.))
index e9d89ca658807c46fbbcf4a849a7222e079d31cc..51e2964fa8355873c47573d0c4a9451ab2f4fccc 100644 (file)
@@ -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:)
index 57c976b6d347bdefdf58be6e85f94dddc1492c0c..bc34a6837f5ec42408fed3061c2fc96025e58759 100644 (file)
@@ -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]");
index 5a40028d74daa817a428dcd8e7d1a92d5a23970e..7348856990e0c99beeb2a0cb4bfacf8a36e21e61 100644 (file)
@@ -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()
 
index 0aacae14d8f1531755edfe08b3595c60d97f986b..861f231057f32e2dd0818b985f44e00de232428c 100644 (file)
@@ -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