Salome HOME
Porting to Python 3 (1st draft)
authorGilles DAVID <gilles-g.david@edf.fr>
Thu, 30 Mar 2017 09:01:32 +0000 (11:01 +0200)
committerGilles DAVID <gilles-g.david@edf.fr>
Thu, 30 Mar 2017 09:01:32 +0000 (11:01 +0200)
src/ATOMGEN/ATOMGEN.py
src/ATOMGEN/ATOMGEN_XmlParser.py
src/ATOMGENGUI/ATOMGENGUI.py

index b5aebe02c6dae1de31a085e3ca9fa96ec65b4bd7..c8440981facef00229f2640623021f5a56fcded8 100644 (file)
@@ -75,12 +75,9 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
         """
         Gets study data
         """
-        if self.studyData.has_key( studyID ):
-            l = []
-            for m in self.studyData[ studyID ]:
-                l.append( m._this() )
-            return l
-        print "ATOMGEN: getData() failed because studyID ", str( studyID ), " was not found"
+        if studyID in self.studyData:
+            return [m._this() for m in self.studyData[studyID]]
+        print("ATOMGEN: getData() failed because studyID ", str( studyID ), " was not found")
         return []
 
     def Save( self, component, URL, isMultiFile ):
@@ -97,14 +94,13 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
         """
         global __entry2IOR__
         __entry2IOR__.clear()
-        import StringIO, pickle
         study = component.GetStudy()
         self.setCurrentStudy( study )
-        iter = study.NewChildIterator(component)
+        iterator = study.NewChildIterator(component)
         data = []
-        while iter.More():
-            sobject = iter.Value()
-            iter.Next()
+        while iterator.More():
+            sobject = iterator.Value()
+            iterator.Next()
             found, attr = sobject.FindAttribute("AttributeName")
             if not found: continue
             from ATOMGEN_Data import Molecule, Atom
@@ -148,7 +144,7 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
     def LocalPersistentIDToIOR(self, sobject, persistentID, isMultiFile, isASCII):
         "Converts persistent ID of the object to its IOR."
         global __entry2IOR__
-        if __entry2IOR__.has_key(persistentID):
+        if persistentID in __entry2IOR__:
             return __entry2IOR__[persistentID]
         return ""
 
@@ -157,7 +153,7 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
         Called when study is closed
         """
         study = component.GetStudy()
-        if study and self.studyData.has_key( study._get_StudyId() ):
+        if study and study._get_StudyId() in self.studyData:
             del self.studyData[ study._get_StudyId() ]
         if study == self.study:
             self.study = None
@@ -231,7 +227,7 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
             studyID = self.study._get_StudyId()
             self.studyData[ studyID ] = []
             self.entry2PyName[ studyID ] = {}
-            print "ATOMGEN: init new arrays for studyID ", str( studyID 
+            print("ATOMGEN: init new arrays for studyID ", str( studyID )
         pass
 
     def importXmlFile( self, fileName ):
@@ -322,12 +318,12 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
                     entries.append(so.GetID())
         # store data
         studyID = self.study._get_StudyId()
-        if self.studyData.has_key( studyID ):
+        if studyID in self.studyData:
             data = self.studyData[ studyID ]
             data += new_data
             self.studyData[ studyID ] = data
             return entries
-        print "ATOMGEN: could not append new data because studyID ", str( studyID ), " was not found"
+        print("ATOMGEN: could not append new data because studyID ", str( studyID ), " was not found")
         return entries
 
     def _translateMolecule( self, mol, i, dx, dy, dz ):
@@ -367,16 +363,16 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
                 script.append(s)
         
         if isMultiFile :
-           script.append(prefix+"pass")
-       else:
-           script.append("\n")
-       script.append("\0")
+            script.append(prefix + "pass")
+        else:
+            script.append("\n")
+        script.append("\0")
         
         all = "\n".join(script)
         self._getPyNames()        
         studyID = self.study._get_StudyId()
         
-        for k in self.entry2PyName[studyID].keys() :
+        for k in list(self.entry2PyName[studyID].keys()) :
             all = all.replace(k,self.entry2PyName[studyID][k])
         
         return (all,1)
@@ -409,13 +405,13 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
         
         studyID = self.study._get_StudyId()
         self.entry2PyName[studyID] = {}
-        iter = self.study.NewChildIterator(self.study.FindComponent(self._ComponentDataType))
-        while iter.More():
-            sobject = iter.Value()
-            iter.Next()            
+        iterator = self.study.NewChildIterator(self.study.FindComponent(self._ComponentDataType))
+        while iterator.More():
+            sobject = iterator.Value()
+            iterator.Next()
             found, attr = sobject.FindAttribute("AttributeName")
             if not found: continue
-            self.entry2PyName[studyID][sobject.GetID()] = self._fixPythonName(attr.Value())            
+            self.entry2PyName[studyID][sobject.GetID()] = self._fixPythonName(attr.Value())
             
     def _fixPythonName(self, in_str):
         """
@@ -437,6 +433,6 @@ class ATOMGEN( ATOMGEN_ORB__POA.ATOMGEN_Gen,
             
         studyID = self.study._get_StudyId()
         
-        if newstring in self.entry2PyName[studyID].values():
+        if newstring in list(self.entry2PyName[studyID].values()):
            newstring = self._fixPythonName( newstring + "_1")
         return newstring
index 4e468a27b9d65b9418596a7f0cb71297ac50302f..50daf3272df10b551d3e30f431037a96b938e2ec 100644 (file)
@@ -74,7 +74,6 @@ def writeXmlFile( filename, data ):
             atomnode.setAttribute( __z_attr__, str( atom.z ) )
             molnode.appendChild( atomnode )
         docnode.appendChild( molnode )
-    file = open( filename, "w" )
-    file.write( doc.toprettyxml() )
-    file.close()
+    with open(filename, "w") as f:
+        f.write(doc.toprettyxml())
     pass
index ac27bc5d446e4506c00d7c27088f682f8f887938..24c7fe7281f272c36639c219d08b9aa5572aba77 100644 (file)
@@ -82,7 +82,7 @@ def processException( e ):
     """
     Prints exception info
     """
-    print "Exception has been caught:", e
+    print("Exception has been caught:", e)
     pass
 
 def warning( message, title = None ):
@@ -126,17 +126,17 @@ def initialize():
     Creates menus, toolbars and performs other internal
     initialization
     """
-    print "ATOMGENGUI::initialize"
+    print("ATOMGENGUI::initialize")
     global __study_data_map__
     # get study id
     studyId = sgPyQt.getStudyId()
-    if not __study_data_map__.has_key( studyId ):
+    if studyId not in __study_data_map__:
         __study_data_map__[ studyId ] = {}
     # get selection object
     selection = sgPyQt.getSelection()
     selection.ClearIObjects()
     __study_data_map__[ studyId ][ "selection" ] = selection
-    print "ATOMGENGUI::initialize done"
+    print("ATOMGENGUI::initialize done")
     pass
 
 def windows():
@@ -146,7 +146,7 @@ def windows():
     Should return a map of the SALOME dockable windows id's
     needed to be opened when module is activated.
     """
-    print "ATOMGENGUI::windows"
+    print("ATOMGENGUI::windows")
     winMap = {}
     winMap[ SalomePyQt.WT_ObjectBrowser ] = Qt.LeftDockWidgetArea
     winMap[ SalomePyQt.WT_PyConsole ]     = Qt.BottomDockWidgetArea
@@ -159,14 +159,14 @@ def views():
     Should return a list of the SALOME view window types
     needed to be opened when module is activated.
     """
-    print "ATOMGENGUI::views"
+    print("ATOMGENGUI::views")
     return None
 
 def activate():
     """
     This method is called when GUI module is being activated.
     """
-    print "ATOMGENGUI::activate"
+    print("ATOMGENGUI::activate")
     # set current study
     global myStudy
     global __study_data_map__
@@ -208,7 +208,7 @@ def deactivate():
     """
     This method is called when GUI module is being deactivated.
     """
-    print "ATOMGENGUI::deactivate"
+    print("ATOMGENGUI::deactivate")
     # connect selection
     global myStudy
     studyId = myStudy._get_StudyId()
@@ -228,7 +228,7 @@ def activeStudyChanged( studyId ):
     (user switches between studies desktops).
     <studyId> is an id of study being activated.
     """
-    print "ATOMGENGUI::activeStudyChanged: study Id =", studyId
+    print("ATOMGENGUI::activeStudyChanged: study Id =", studyId)
     global myStudy
     if myStudy and myStudy._get_StudyId() == studyId:
         return
@@ -245,7 +245,7 @@ def createPopupMenu( popup, context ):
     Should analyze the selection and fill in the popup menu
     with the corresponding actions
     """
-    print "ATOMGENGUI::createPopupMenu: popup =", popup, "; context =", context
+    print("ATOMGENGUI::createPopupMenu: popup =", popup, "; context =", context)
     selected = selectedItems()
     isOk = False
     for entry in selected:
@@ -265,14 +265,14 @@ def OnGUIEvent( commandId ):
     This method is called when user activates some GUI action
     <commandId> is an ID of the GUI action.
     """
-    print "ATOMGENGUI::OnGUIEvent: commandId =", commandId
-    if dict_command.has_key( commandId ):
+    print("ATOMGENGUI::OnGUIEvent: commandId =", commandId)
+    if commandId in dict_command:
         try:
             dict_command[ commandId ]()
-        except Exception, e:
+        except Exception as e:
             processException( e )
     else:
-       print "ATOMGENGUI::OnGUIEvent: Action is not implemented: ", commandId
+       print("ATOMGENGUI::OnGUIEvent: Action is not implemented: ", commandId)
     pass
 
 ################################################
@@ -289,7 +289,7 @@ class RunDlg(QDialog, Ui_RunDlg):
         Constructor
         """
         QDialog.__init__(self, sgPyQt.getDesktop())
-       self.setupUi(self)
+        self.setupUi(self)
         self.onCheckAll()
         self.selected = []
         self.selectionChanged()
@@ -379,14 +379,14 @@ def selectionChanged():
     Global selection changed slot
     """
     selected = selectedItems()
-    print "--> Selected objects: %d"%len(selected)
+    print("--> Selected objects: %d"%len(selected))
     pass
 
 def onImportXml():
     """
     Import XML file action slot
     """
-    print "--> onImportXml() is started"
+    print("--> onImportXml() is started")
     filters = []
     filters.append( tr( "XML_FILES" ) )
     fileName = sgPyQt.getFileName( sgPyQt.getDesktop(),
@@ -394,21 +394,21 @@ def onImportXml():
                                    filters,
                                    tr( "IMPORT_XML" ),
                                    True )
-    fileName = unicode(fileName)
+    fileName = str(fileName)
 
     if len(fileName) > 0 :
         if not _getEngine().importXmlFile( str( fileName ) ):
             warning( "IMPORT_ERROR" )
         else:
             sgPyQt.updateObjBrowser()
-    print "--> onImportXml() is finished"
+    print("--> onImportXml() is finished")
     pass
 
 def onExportXml():
     """
     Export XML file action slot
     """
-    print "--> onExportXml() is started"
+    print("--> onExportXml() is started")
     filters = []
     filters.append( tr( "XML_FILES" ) )
     fileName = sgPyQt.getFileName( sgPyQt.getDesktop(),
@@ -416,23 +416,23 @@ def onExportXml():
                                    filters,
                                    tr( "EXPORT_XML" ),
                                    False )
-    fileName = unicode(fileName)
+#     fileName = str(fileName)
 
     if len(fileName) > 0 :
-        if not _getEngine().exportXmlFile( str( fileName ) ):
+        if not _getEngine().exportXmlFile(fileName):
             warning( "EXPORT_ERROR" )
-    print "--> onExportXml() is finished"
+    print("--> onExportXml() is finished")
     pass
 
 def onRunAlgo():
-    print "--> onRunAlgo() is started !!!"
+    print("--> onRunAlgo() is started !!!")
     global myRunDlg
     if not myRunDlg:
         myRunDlg = RunDlg()
     myRunDlg.show()
     myRunDlg.activateWindow()
     myRunDlg.setFocus()
-    print "--> onRunAlgol() is finished"
+    print("--> onRunAlgol() is finished")
     pass
 
 ################################################