Salome HOME
[PYTHON 3] 1st draft
authorNicolas Geimer <nicolas.geimer@edf.fr>
Fri, 10 Feb 2017 15:57:29 +0000 (16:57 +0100)
committerNicolas Geimer <nicolas.geimer@edf.fr>
Mon, 27 Feb 2017 10:10:05 +0000 (11:10 +0100)
112 files changed:
bin/NSparam.py
bin/ORBConfigFile.py
bin/PortManager.py
bin/addToKillList.py
bin/appli_gen.py
bin/appliskel/getAppliPath.py
bin/appliskel/kill_remote_containers.py
bin/appliskel/salome
bin/appliskel/salome_starter.py
bin/appliskel/salome_tester/salome_instance.py
bin/appliskel/salome_tester/salome_test_driver.py
bin/appliskel/salome_tester/salome_test_driver_gui.py
bin/appliskel/tests/concurrentSession/TestConcurrentSession.py
bin/appliskel/tests/concurrentSession/TestMinimalExample.py
bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py
bin/appliskel/tests/salomeCommand/TestLauncherSimple.py
bin/appliskel/tests/salomeInstance/instances.py
bin/appliskel/update_catalogs.py
bin/killSalome.py
bin/killSalomeWithPort.py
bin/launchConfigureParser.py
bin/nameserver.py
bin/orbmodule.py
bin/parseConfigFile.py
bin/runConsole.py
bin/runSalome.py
bin/runSession.py
bin/runTests.py
bin/salomeContext.py
bin/salomeContextUtils.py.in
bin/salome_utils.py
bin/searchFreePort.py
bin/server.py
bin/setenv.py
bin/virtual_salome.py
bin/waitContainers.py
doc/salome/tui/pythfilter.py
salome_adm/prepare_generating_doc.py
src/AppQuickStart/app-quickstart.py
src/AppQuickStart/app-template/src/tests/helloWorld.py
src/Container/Container_i.cxx
src/Container/Container_init_python.cxx
src/Container/SALOME_ComponentPy.py
src/Container/SALOME_Container.py
src/Container/SALOME_ContainerPy.py
src/Container/SALOME_PyNode.py
src/DSC/DSC_Python/calcium.i
src/KERNEL_PY/Help.py
src/KERNEL_PY/PyInterp.py
src/KERNEL_PY/__init__.py
src/KERNEL_PY/batchmode_salome.py
src/KERNEL_PY/iparameters.py
src/KERNEL_PY/kernel/__init__.py
src/KERNEL_PY/kernel/datamodeler.py
src/KERNEL_PY/kernel/diclookup.py
src/KERNEL_PY/kernel/enumerate.py
src/KERNEL_PY/kernel/parametric/study_exchange_vars.py
src/KERNEL_PY/kernel/pyunittester.py
src/KERNEL_PY/kernel/services.py
src/KERNEL_PY/kernel/studyedit.py
src/KERNEL_PY/kernel/syshelper.py
src/KERNEL_PY/kernel/termcolor.py
src/KERNEL_PY/kernel/testdata.py
src/KERNEL_PY/kernel/threadhelper.py
src/KERNEL_PY/kernel/uiexception.py
src/KERNEL_PY/kernel/unittester.py
src/KERNEL_PY/omnipatch.py
src/KERNEL_PY/salome_ComponentGUI.py
src/KERNEL_PY/salome_iapp.py
src/KERNEL_PY/salome_notebook.py
src/KERNEL_PY/salome_pynode.py
src/KERNEL_PY/salome_study.py
src/KERNEL_PY/salome_test.py
src/KERNEL_PY/salome_version.py
src/KernelHelpers/Test/TestKernelHelpers.py
src/Launcher/Test/test_launcher.py
src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py
src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py
src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py
src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py
src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i
src/Logger/SALOME_Trace.py
src/Logger/Test/TestKiller.py
src/MPIContainer/MPIContainer_i.cxx
src/ModuleCatalog/TestModuleCatalog.py
src/ModuleGenerator/IDLparser.py
src/NamingService/SALOME_NamingServicePy.py
src/NamingService/Test/TestNamingService.py
src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx
src/ParallelContainer/SALOME_ParallelContainer_i.cxx
src/SALOMEDS/Test/TestSALOMEDS.py
src/SALOMEDSImpl/Test/TestSALOMEDSImpl.py
src/SALOMELocalTrace/Test/TestSALOMELocalTrace.py
src/SALOMESDS/SALOMEGlobalVarHelper.py
src/SALOMESDS/SALOMESDS_DataScopeServer.cxx
src/SALOMESDS/SALOMESDS_PickelizedPyObjRdExtServer.cxx
src/SALOMESDS/SALOMESDS_PickelizedPyObjRdWrServer.cxx
src/SALOMESDS/SALOMESDS_PickelizedPyObjServer.cxx
src/SALOMESDS/SALOMEWrappedStdType.py
src/SALOMESDS/SalomeSDSClt.py
src/SALOMESDS/TestSalomeSDS.py
src/SALOMESDS/TestSalomeSDS1.py
src/SALOMESDS/TestSalomeSDSHelper0.py
src/SALOMETraceCollector/Test/TestSALOMETraceCollector.py
src/TestContainer/SALOME_TestComponentPy.py
src/TestContainer/TestComponentPy.py
src/UnitTests/UnitTests.py
src/UnitTests/prepare_test.py
src/Utils/CMakeLists.txt
src/Utils/Test/TestUtils.py
src/Utils/Utils_Identity.py
src/Utils/capsulethunk.h [new file with mode: 0644]

index 3cb3cf9cd4da95209569a2f2a17d0df8262172db..a9f9bdff92c192e430393ba6d8eb5453323f5bf3 100755 (executable)
@@ -56,12 +56,12 @@ if __name__ == "__main__":
         if sys.argv[1]=='host':
             my_host = getNSparams('host')
             # keep print, stdout used in shell
-            print my_host
+            print(my_host)
             pass
         elif sys.argv[1]=='port':
             my_port = getNSparams('port')
             # keep print, stdout used in shell
-            print my_port
+            print(my_port)
             pass
         else:
             my_host, my_port = getNSparams()
@@ -70,7 +70,7 @@ if __name__ == "__main__":
     else:
         getNSparams()
         # keep print, stdout used in shell
-        print my_host, my_port
+        print(my_host, my_port)
         pass
     pass
 #
index 19a9647f44e57417b2c575eca00f15d47ed6c951..a432543cc0dd6eec875688d172acad9736d06ab6 100644 (file)
@@ -98,4 +98,4 @@ if __name__ == "__main__":
   # RETURN_VALUE_2=$(echo ${RETURN_VALUES} | cut -d' ' -f2)
   # ...
   # IMPORTANT NOTE: this print call MUST BE the first one!!
-  print filename, msgSize
+  print(filename, msgSize)
index 53ebacea9a7c9e86b59bd0958ee0b1234407c87c..c23c28d51348342dd9b38adde8e334781b448ebd 100644 (file)
@@ -101,14 +101,14 @@ def __isNetworkConnectionActiveOnPort(port):
     p = Popen(cmd, stdout=PIPE, stderr=STDOUT)
     out, err = p.communicate()
   except:
-    print "Error when trying to access active network connections."
-    if err: print err
+    print("Error when trying to access active network connections.")
+    if err: print(err)
     import traceback
     traceback.print_exc()
     return False
 
-  import StringIO
-  buf = StringIO.StringIO(out)
+  from io import StringIO
+  buf = StringIO(out.decode())
   ports = buf.readlines()
   # search for TCP - LISTEN connections
   import re
@@ -135,7 +135,7 @@ def getPort(preferedPort=None):
     config = {'busy_ports':[]}
     logger.debug("read configuration file")
     try:
-      with open(config_file, 'r') as f:
+      with open(config_file, 'rb') as f:
         config = pickle.load(f)
     except:
       logger.info("Problem loading PortManager file: %s"%config_file)
@@ -153,7 +153,7 @@ def getPort(preferedPort=None):
           msg  = "\n"
           msg += "Can't find a free port to launch omniNames\n"
           msg += "Try to kill the running servers and then launch SALOME again.\n"
-          raise RuntimeError, msg
+          raise RuntimeError(msg)
         logger.debug("Port %s seems to be busy"%str(port))
         if not port in config["busy_ports"]:
           config["busy_ports"].append(port)
@@ -164,7 +164,7 @@ def getPort(preferedPort=None):
     # write config
     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
     try:
-      with open(config_file, 'w') as f:
+      with open(config_file, 'wb') as f:
         pickle.dump(config, f)
     except IOError:
       pass
@@ -192,7 +192,7 @@ def releasePort(port):
     config = {'busy_ports':[]}
     logger.debug("read configuration file")
     try:
-      with open(config_file, 'r') as f:
+      with open(config_file, 'rb') as f:
         config = pickle.load(f)
     except IOError: # empty file
       pass
@@ -209,7 +209,7 @@ def releasePort(port):
     # write config
     logger.debug("write busy_ports: %s"%str(config["busy_ports"]))
     try:
-      with open(config_file, 'w') as f:
+      with open(config_file, 'wb') as f:
         pickle.dump(config, f)
     except IOError:
       pass
@@ -234,7 +234,7 @@ def getBusyPorts():
     config = {'busy_ports':[]}
     logger.debug("read configuration file")
     try:
-      with open(config_file, 'r') as f:
+      with open(config_file, 'rb') as f:
         config = pickle.load(f)
     except IOError: # empty file
       pass
index ca2abd93412ec2f67940379ce0158d5314c564f4..685c9e9796f2f7c68b047bc920b0bbc5c7c4eade 100755 (executable)
@@ -34,7 +34,7 @@ def findFileDict():
     """
     from salome_utils import getPortNumber
     port = getPortNumber()
-    if verbose(): print "myport = ", port
+    if verbose(): print("myport = ", port)
     return port
 
 def addToKillList(command_pid, command, port=None):
@@ -60,7 +60,7 @@ def addToKillList(command_pid, command, port=None):
     # check if PID is already in dictionary
     already_in=False
     for process_id in process_ids:
-        for pid in process_id.keys():
+        for pid in list(process_id.keys()):
             if int(pid) == int(command_pid):
                 already_in=True
                 break
@@ -71,17 +71,17 @@ def addToKillList(command_pid, command, port=None):
     # add process to the dictionary
     if not already_in:
         import types
-        if type(command) == types.ListType: command=" ".join([str(c) for c in command])
+        if type(command) == list: command=" ".join([str(c) for c in command])
         command=command.split()[0]
         try:
-            if verbose(): print "addToKillList: %s : %s" % ( str(command_pid), command )
+            if verbose(): print("addToKillList: %s : %s" % ( str(command_pid), command ))
             process_ids.append({int(command_pid): [command]})
             dir = os.path.dirname(filedict)
-            if not os.path.exists(dir): os.makedirs(dir, 0777)
+            if not os.path.exists(dir): os.makedirs(dir, 0o777)
             with open(filedict,'w') as fpid:
                 pickle.dump(process_ids, fpid)
         except:
-            if verbose(): print "addToKillList: can not add command %s : %s to the kill list" % ( str(command_pid), command )
+            if verbose(): print("addToKillList: can not add command %s : %s to the kill list" % ( str(command_pid), command ))
             pass
         pass
     pass
@@ -110,11 +110,11 @@ def killList(port=None):
     # kill processes
     for process_id in process_ids:
         #print process_id
-        for pid, cmd in process_id.items():
+        for pid, cmd in list(process_id.items()):
             try:
                 os.kill(int(pid),signal.SIGKILL)
             except:
-                print "  ------------------ process %s : %s inexistant"% (pid, cmd[0])
+                print("  ------------------ process %s : %s inexistant"% (pid, cmd[0]))
                 pass
             pass
         pass
@@ -123,6 +123,6 @@ def killList(port=None):
     pass
 
 if __name__ == "__main__":
-    if verbose(): print sys.argv
+    if verbose(): print(sys.argv)
     addToKillList(sys.argv[1], sys.argv[2])
     pass
index 4e04d1d3256f84712f93c8ac0c82fc4dbd295b5f..f78d20d2458d86d0901502daeb0d5962d40762ca 100644 (file)
@@ -63,7 +63,7 @@ gui_att  = "gui"
 
 class xml_parser:
     def __init__(self, fileName ):
-        print "Configure parser: processing %s ..." % fileName
+        print("Configure parser: processing %s ..." % fileName)
         self.space = []
         self.config = {}
         self.config["modules"] = []
@@ -182,21 +182,21 @@ def install(prefix, config_file, verbose=0):
     try:
         parser = xml_parser(filename)
         _config = parser.config
-    except xml.sax.SAXParseException, inst:
-        print inst.getMessage()
-        print "Configure parser: parse error in configuration file %s" % filename
+    except xml.sax.SAXParseException as inst:
+        print(inst.getMessage())
+        print("Configure parser: parse error in configuration file %s" % filename)
         pass
-    except xml.sax.SAXException, inst:
-        print inst.args
-        print "Configure parser: error in configuration file %s" % filename
+    except xml.sax.SAXException as inst:
+        print(inst.args)
+        print("Configure parser: error in configuration file %s" % filename)
         pass
     except:
-        print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
+        print("Configure parser: Error : can not read configuration file %s, check existence and rights" % filename)
         pass
 
     if verbose:
-        for cle,val in _config.items():
-            print cle, val
+        for cle,val in list(_config.items()):
+            print(cle, val)
             pass
 
     # Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
@@ -207,8 +207,8 @@ def install(prefix, config_file, verbose=0):
       pass
 
     for module in _config.get("modules", []):
-        if _config.has_key(module):
-            print "--- add module ", module, _config[module]
+        if module in _config:
+            print("--- add module ", module, _config[module])
             options = params()
             options.verbose = verbose
             options.clear = 0
@@ -220,8 +220,8 @@ def install(prefix, config_file, verbose=0):
         pass
 
     for extra_test in _config.get("extra_tests", []):
-        if _config.has_key(extra_test):
-            print "--- add extra test ", extra_test, _config[extra_test]
+        if extra_test in _config:
+            print("--- add extra test ", extra_test, _config[extra_test])
             options = params()
             options.verbose = verbose
             options.clear = 0
@@ -264,31 +264,31 @@ def install(prefix, config_file, verbose=0):
     # Creation of env.d directory
     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
 
-    if _config.has_key("prereq_path") and os.path.isfile(_config["prereq_path"]):
+    if "prereq_path" in _config and os.path.isfile(_config["prereq_path"]):
         shutil.copyfile(_config["prereq_path"],
                         os.path.join(home_dir, 'env.d', 'envProducts.sh'))
         pass
     else:
-        print "WARNING: prerequisite file does not exist"
+        print("WARNING: prerequisite file does not exist")
         pass
 
-    if _config.has_key("context_path") and os.path.isfile(_config["context_path"]):
+    if "context_path" in _config and os.path.isfile(_config["context_path"]):
         shutil.copyfile(_config["context_path"],
                         os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
         pass
     else:
-        print "WARNING: context file does not exist"
+        print("WARNING: context file does not exist")
         pass
 
-    if _config.has_key("sha1_collect_path") and os.path.isfile(_config["sha1_collect_path"]):
+    if "sha1_collect_path" in _config and os.path.isfile(_config["sha1_collect_path"]):
         shutil.copyfile(_config["sha1_collect_path"],
                         os.path.join(home_dir, 'sha1_collections.txt'))
         pass
     else:
-        print "WARNING: context file does not exist"
+        print("WARNING: context file does not exist")
         pass
 
-    if _config.has_key("system_conf_path") and os.path.isfile(_config["system_conf_path"]):
+    if "system_conf_path" in _config and os.path.isfile(_config["system_conf_path"]):
         shutil.copyfile(_config["system_conf_path"],
                         os.path.join(home_dir, 'env.d', 'envConfSystem.sh'))
         pass
@@ -299,11 +299,11 @@ def install(prefix, config_file, verbose=0):
             command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
             f.write(command)
             pass
-        if _config.has_key("samples_path"):
+        if "samples_path" in _config:
             command = 'export DATA_DIR=' + _config["samples_path"] +'\n'
             f.write(command)
             pass
-        if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
+        if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
             command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
             f.write(command)
 
@@ -315,11 +315,11 @@ def install(prefix, config_file, verbose=0):
             command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
             f.write(command)
             pass
-        if _config.has_key("samples_path"):
+        if "samples_path" in _config:
             command = 'DATA_DIR=' + _config["samples_path"] +'\n'
             f.write(command)
             pass
-        if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
+        if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
             command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
             f.write(command)
 
@@ -376,7 +376,7 @@ MMGT_REENTRANT=1
     #Add USERS directory with 777 permission to store users configuration files
     users_dir = os.path.join(home_dir,'USERS')
     makedirs(users_dir)
-    os.chmod(users_dir, 0777)
+    os.chmod(users_dir, 0o777)
 
 def main():
     parser = optparse.OptionParser(usage=usage)
@@ -392,7 +392,7 @@ def main():
 
     options, args = parser.parse_args()
     if not os.path.exists(options.config):
-        print "ERROR: config file %s does not exist. It is mandatory." % options.config
+        print("ERROR: config file %s does not exist. It is mandatory." % options.config)
         sys.exit(1)
 
     install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
index b17367163ccba92bdf973aef1d45e823dcc379af..460f5c592dc4a8f5890c212b5f5636f6cc1bc5b2 100755 (executable)
@@ -36,7 +36,7 @@ def relpath(target, base):
     """
     target=target.split(os.path.sep)
     base=base.split(os.path.sep)
-    for i in xrange(len(base)):
+    for i in range(len(base)):
       if base[i] != target[i]:
         i=i-1
         #not in base
@@ -61,5 +61,5 @@ if __name__ == "__main__":
         applipath = relpath(os.path.realpath(os.path.dirname(__file__)),os.path.realpath(os.getenv('HOME')))
     else:
         applipath = get_appli_path()
-    print applipath
+    print(applipath)
 #
index 06bcffb4a418b649b8ac9f252fc8c4752e38d319..4c3a39429a31dd7551a5a5817ce5e2e45bb421b4 100755 (executable)
@@ -118,7 +118,7 @@ def main():
   options, args = parser.parse_args()
 
   if not os.path.exists(catalog_file):
-    print "ERROR: the catalog file %s is mandatory" % catalog_file_base
+    print("ERROR: the catalog file %s is mandatory" % catalog_file_base)
     sys.exit(1)
 
   #Parse CatalogResource.xml
@@ -147,7 +147,7 @@ def main():
     else:
       port=os.getenv("NSPORT") or "2810"
     command=command+ " " + get_hostname() + " " + port +" killSalomeWithPort.py " + port
-    print command
+    print(command)
     os.system(command)
 
 if __name__ == '__main__':
index 171036b0e1e041a36aa0069af4c5490c113e907a..e14ccae287179a9333124674f072cefac0f3b5ae 100755 (executable)
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
 
 # Copyright (C) 2013-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 #
@@ -38,7 +38,7 @@ def main(args):
   configFileNames, args, unexisting = getConfigFileNames(args, checkExistence=True)
 
   if len(unexisting) > 0:
-    print "ERROR: unexisting configuration/environment file(s): " + ', '.join(unexisting)
+    print("ERROR: unexisting configuration/environment file(s): " + ', '.join(unexisting))
     sys.exit(1)
 
   # Create a SalomeContext which parses configFileNames to initialize environment
@@ -61,7 +61,7 @@ def main(args):
       sys.stderr.write(err)
     #print 'Thank you for using SALOME!'
     sys.exit(returncode)
-  except SalomeContextException, e:
+  except SalomeContextException as e:
     import logging
     logging.getLogger("salome").error(e)
     sys.exit(1)
index b381b89c9c990fa4fe017da129d6d431bfd81c3f..97f355e6bb3717aee25285aef382ec67cf42990a 100644 (file)
@@ -53,7 +53,7 @@ def initialize(launcherPath, launcherFile):
   appliPath = __detectAppliPath(launcherPath, launcherFile)
 
   if appliPath is None:
-    print "ERROR: Unable to find application folder"
+    print("ERROR: Unable to find application folder")
     sys.exit(0)
 
   appliPath = os.path.relpath(appliPath, homePath)
@@ -68,7 +68,7 @@ def initialize(launcherPath, launcherFile):
   try:
     from salomeContextUtils import setOmniOrbUserPath
     setOmniOrbUserPath()
-  except Exception, e:
-    print e
+  except Exception as e:
+    print(e)
     sys.exit(1)
 # End of preliminary work
index 8fb347e928580f7b8502438a1abed63a3d8fda2f..740138b2a127d89918b2eddf06f02d7a9fee9371 100644 (file)
@@ -102,11 +102,11 @@ class SalomeInstance(object):
 #
 
 if __name__ == "__main__":
-  print "##### Start instance..."
+  print("##### Start instance...")
   salome_instance = SalomeInstance.start()
   port = salome_instance.get_port()
-  print "#####    ...instance started on port %s"%port
+  print("#####    ...instance started on port %s"%port)
 
-  print "##### Terminate instance running on port %s"%port
+  print("##### Terminate instance running on port %s"%port)
   salome_instance.stop()
 #
index 60b8fd9a20d347d99529d7db00bd946d4c80adb2..e4dbcd157c70f281e3ebf7ecebd8c7489411584e 100644 (file)
@@ -28,13 +28,27 @@ import signal
 
 # Run test
 def runTest(command):
-  print "Running:", " ".join(command)
-  p = subprocess.Popen(command)
-  p.communicate()
+  print("Running:", " ".join(command))
+  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+  out, err = p.communicate()
   res = p.returncode
   # About res value:
   # A negative value -N indicates that the child was terminated by signal N (Unix only).
   # On Unix, the value 11 generally corresponds to a segmentation fault.
+  return res, out, err
+#
+
+# Display output and errors
+def processResult(res, out, err):
+  if out:
+    print(out)
+    pass
+  if err:
+    print("    ** Detected error **")
+    print("Error code: ", res)
+    print(err, end=' ')
+    print("    ** end of message **")
+    pass
   return res
 #
 
@@ -53,7 +67,7 @@ if __name__ == "__main__":
   # Add explicit call to python executable if a Python script is passed as
   # first argument
   if not args:
-    print "Invalid arguments for salome_test_driver.py. No command defined."
+    print("Invalid arguments for salome_test_driver.py. No command defined.")
     exit(1)
   _, ext = os.path.splitext(args[0])
   if ext == ".py":
@@ -66,7 +80,7 @@ if __name__ == "__main__":
   setOmniOrbUserPath()
 
   # Set timeout handler
-  print "Test timeout explicitely set to: %s seconds"%timeout_delay
+  print("Test timeout explicitely set to: %s seconds"%timeout_delay)
   timeout_sec = abs(int(timeout_delay)-10)
   if sys.platform == 'win32':
     from threading import Timer
@@ -82,9 +96,10 @@ if __name__ == "__main__":
   try:
     salome_instance = SalomeInstance.start(shutdown_servers=True)
     port = salome_instance.get_port()
-    res = runTest(test_and_args)
+    res, out, err = runTest(test_and_args)
+    res = processResult(res, out, err)
   except TimeoutException:
-    print "FAILED : timeout(%s) is reached"%timeout_delay
+    print("FAILED : timeout(%s) is reached"%timeout_delay)
   except:
     import traceback
     traceback.print_exc()
@@ -93,6 +108,6 @@ if __name__ == "__main__":
   salome_instance.stop()
   if sys.platform == 'win32':
     timer.cancel()
-  print "Exit test with status code:", res
+  print("Exit test with status code:", res)
   exit(res)
 #
index 284f9e6247e85ac0b709aabe0d16821e0d928085..777b17798ede937319cdfdf4477d9d81b773ba1c 100644 (file)
@@ -41,7 +41,7 @@ if __name__ == "__main__":
   # Add explicit call to python executable if a Python script is passed as
   # first argument
   if not args:
-    print "Invalid arguments for salome_test_driver_gui.py. No command defined."
+    print("Invalid arguments for salome_test_driver_gui.py. No command defined.")
     exit(1)
   _, ext = os.path.splitext(args[0])
   test_and_args = args
@@ -51,7 +51,7 @@ if __name__ == "__main__":
   setOmniOrbUserPath()
 
   # Set timeout handler
-  print "Test timeout explicitely set to: %s seconds"%timeout_delay
+  print("Test timeout explicitely set to: %s seconds"%timeout_delay)
   timeout_sec = abs(int(timeout_delay)-10)
   if sys.platform == 'win32':
     from threading import Timer
@@ -66,7 +66,7 @@ if __name__ == "__main__":
   try:
     salome_instance = SalomeInstance.start(with_gui=True, args=test_and_args)
   except TimeoutException:
-    print "FAILED : timeout(%s) is reached"%timeout_delay
+    print("FAILED : timeout(%s) is reached"%timeout_delay)
   except:
     import traceback
     traceback.print_exc()
index 2a8a1275f8b546dd771b0b1f1c146ffa9d4ff775..d0c066081881fbff7d5c8819b1b805370211f65b 100644 (file)
@@ -23,14 +23,14 @@ import tempfile
 import os
 import sys
 import imp
-from cStringIO import StringIO
+from io import StringIO
 import multiprocessing
 import logging
 
 def new_instance(running_instances):
   from salome_instance import SalomeInstance
   instance = SalomeInstance.start()
-  print "Instance created and now running on port", instance.get_port()
+  print("Instance created and now running on port", instance.get_port())
   running_instances.put(instance)
 #
 
@@ -46,7 +46,7 @@ class TestConcurrentLaunch(unittest.TestCase):
   def __terminateInstances(self, running_instances):
     while not running_instances.empty():
       instance = running_instances.get()
-      print "Terminate instance running on port", instance.get_port()
+      print("Terminate instance running on port", instance.get_port())
       instance.stop()
   #
 
@@ -59,7 +59,7 @@ class TestConcurrentLaunch(unittest.TestCase):
       setenv.main(True, exeName="salome start")
       import runSalome
       runSalome.runSalome()
-    except SystemExit, e:
+    except SystemExit as e:
       if str(e) != '0':
         logging.error(e)
       pass
@@ -73,17 +73,17 @@ class TestConcurrentLaunch(unittest.TestCase):
       import runSession
       params, args = runSession.configureSession(args, exe="salome shell")
       return runSession.runSession(params, args)
-    except SystemExit, e:
+    except SystemExit as e:
       if str(e) != '0':
         logging.error(e)
       pass
   #
   def test01_SingleSession(self):
-    print "** Testing single session **"
+    print("** Testing single session **")
     self.session(["hello.py"])
   #
   def test02_MultiSession(self):
-    print "** Testing multi sessions **"
+    print("** Testing multi sessions **")
     jobs = []
     for i in range(9):
       p = multiprocessing.Process(target=self.session, args=(["hello.py"],))
@@ -94,7 +94,7 @@ class TestConcurrentLaunch(unittest.TestCase):
       j.join()
   #
   def test03_SingleAppli(self):
-    print "** Testing single appli **"
+    print("** Testing single appli **")
     running_instances, processes = self.__createInstances(1)
     for p in processes:
       p.start()
@@ -107,7 +107,7 @@ class TestConcurrentLaunch(unittest.TestCase):
     self.__terminateInstances(running_instances)
   #
   def test04_MultiAppli(self):
-    print "** Testing multi appli **"
+    print("** Testing multi appli **")
     running_instances, processes = self.__createInstances(9)
     for p in processes:
       p.start()
index 0164535406b123eddb3caa111a8109225f44fb21..713f3ad96f9c40368f3616e925a6bd4dec479a2f 100644 (file)
@@ -30,7 +30,7 @@ def port_reservation(obtained_ports, prefered=None, test=None, expected=None):
     port = getPort(prefered)
   else:
     port = getPort()
-  print "obtained port = %s"%port
+  print("obtained port = %s"%port)
 
   obtained_ports.put(port)
 
@@ -41,8 +41,8 @@ def port_reservation(obtained_ports, prefered=None, test=None, expected=None):
 class TestMinimalExample(unittest.TestCase):
   def testSequential(self):
     from PortManager import releasePort, getBusyPorts
-    print "\nBEGIN testSequential"
-    print "Busy ports", getBusyPorts()
+    print("\nBEGIN testSequential")
+    print("Busy ports", getBusyPorts())
     obtained_ports = multiprocessing.Queue()
 
     processes = [
@@ -56,7 +56,7 @@ class TestMinimalExample(unittest.TestCase):
     for p in processes:
       p.join()
 
-    print "Busy ports", getBusyPorts()
+    print("Busy ports", getBusyPorts())
     # Try to get specific port number
     p = multiprocessing.Process(target=port_reservation, args=(obtained_ports, 2872, self, 2872,))
     p.start()
@@ -73,7 +73,7 @@ class TestMinimalExample(unittest.TestCase):
     p.join()
 
     # Release port
-    print "release port 2812"
+    print("release port 2812")
     p = multiprocessing.Process(target=releasePort, args=(2812,))
     p.start()
     p.join()
@@ -84,21 +84,21 @@ class TestMinimalExample(unittest.TestCase):
     p.join()
 
     # Release ports
-    print "Busy ports", getBusyPorts()
+    print("Busy ports", getBusyPorts())
     while not obtained_ports.empty():
       port = obtained_ports.get()
-      print "release port", port
+      print("release port", port)
       p = multiprocessing.Process(target=releasePort, args=(port,))
       p.start()
       p.join()
 
-    print "END testSequential"
+    print("END testSequential")
   #
 
   def testConcurrent(self):
     from PortManager import releasePort, getBusyPorts
-    print "\nBEGIN testConcurrent"
-    print "Busy ports", getBusyPorts()
+    print("\nBEGIN testConcurrent")
+    print("Busy ports", getBusyPorts())
     obtained_ports = multiprocessing.Queue()
     processes = [
       multiprocessing.Process(target=port_reservation, args=(obtained_ports,))
@@ -125,15 +125,15 @@ class TestMinimalExample(unittest.TestCase):
       p.join()
 
     # Release ports
-    print "Busy ports", getBusyPorts()
+    print("Busy ports", getBusyPorts())
     while not obtained_ports.empty():
       port = obtained_ports.get()
-      print "release port", port
+      print("release port", port)
       p = multiprocessing.Process(target=releasePort, args=(port,))
       p.start()
       p.join()
 
-    print "END testConcurrent"
+    print("END testConcurrent")
   #
 #
 
index d6cd97541554e773ed1bb037057d3899e835f69f..4a9f365a003578df01aef538f9cb92f3ec7aa072 100644 (file)
@@ -22,7 +22,7 @@ import unittest
 import os
 import sys
 import imp
-from cStringIO import StringIO
+from io import StringIO
 import logging
 
 logger = logging.getLogger("TestLauncherLogger")
@@ -71,7 +71,7 @@ class TestSessionArgs(unittest.TestCase):
       import runSession
       params, args = runSession.configureSession(args, exe="salome shell")
       return runSession.runSession(params, args)
-    except SystemExit, e:
+    except SystemExit as e:
       if str(e) != '0':
         logger.error(e)
       import traceback
index f235a0a1eb1f47ce57a2ff34663a0efc0a0c8282..a684a6cddc0405d03599540c07ec5b51586bee9e 100644 (file)
@@ -25,11 +25,11 @@ class TestLauncher(unittest.TestCase):
   def setUp(self):
     from salome_instance import SalomeInstance
     self.instance = SalomeInstance.start()
-    print "Instance created and now running on port", self.instance.get_port()
+    print("Instance created and now running on port", self.instance.get_port())
    #
 
   def tearDown(self):
-    print "Terminate instance running on port", self.instance.get_port()
+    print("Terminate instance running on port", self.instance.get_port())
     self.instance.stop()
   #
 
@@ -41,7 +41,7 @@ class TestLauncher(unittest.TestCase):
       args = ["hello.py"]
       params, args = runSession.configureSession(args, exe="salome shell")
       return runSession.runSession(params, args)
-    except SystemExit, e:
+    except SystemExit as e:
       if str(e) != '0':
         logging.error(e)
   #
index 8184677366a75cee31980cca03471ec67daac7a1..50ecfa80d7b90528fb0cce416b08ec040495988a 100644 (file)
@@ -23,7 +23,7 @@ import multiprocessing
 def new_instance(running_instances):
   from salome_instance import SalomeInstance
   instance = SalomeInstance.start()
-  print "Instance created and now running on port", instance.get_port()
+  print("Instance created and now running on port", instance.get_port())
   running_instances.put(instance)
 #
 
@@ -41,7 +41,7 @@ class TestLauncher(unittest.TestCase):
   def __terminateInstances(self, running_instances):
     while not running_instances.empty():
       instance = running_instances.get()
-      print "Terminate instance running on port", instance.get_port()
+      print("Terminate instance running on port", instance.get_port())
       instance.stop()
   #
 
@@ -92,18 +92,18 @@ class TestLauncher(unittest.TestCase):
     # Connect to one instance
     import runConsole
     port = all_instances[len(all_instances)/2].get_port()
-    print "Connect to instance running on port", port
+    print("Connect to instance running on port", port)
     self.__connectToInstance(port)
 
     # Connect to another instance
     import runConsole
     port = all_instances[len(all_instances)/4].get_port()
-    print "Connect to instance running on port", port
+    print("Connect to instance running on port", port)
     self.__connectToInstance(port)
 
     # Terminate instances
     for instance in all_instances:
-      print "Terminate instance running on port", instance.get_port()
+      print("Terminate instance running on port", instance.get_port())
       instance.stop()
   #
 
index 82fce4834b27535c44b801276b905f6a677eead5..8555e0c461351afb2ebe10ad0f4298f860cea4c8 100644 (file)
@@ -155,11 +155,11 @@ class Resource:
       os.mkdir(resource_dir)
       cata_path=os.path.join(appliPath,"share","salome","resources","*Catalog.xml")
       cmd="cp %s %s" % (cata_path,resource_dir)
-      print cmd
+      print(cmd)
       os.system(cmd)
       cata_path=os.path.join(appliPath,"share","salome","resources","*","*Catalog.xml")
       cmd="cp %s %s" % (cata_path,resource_dir)
-      print cmd
+      print(cmd)
       os.system(cmd)
     else:
       #remote machine, use rcopy
@@ -167,12 +167,12 @@ class Resource:
       cata_path=os.path.join(appliPath,"share","salome","resources","*Catalog.xml")
       cmd="%s %s@%s:%s %s"
       cmd= cmd%(rcopy,userName,hostname,cata_path,resource_dir)
-      print cmd
+      print(cmd)
       os.system(cmd)
       cata_path=os.path.join(appliPath,"share","salome","resources","*","*Catalog.xml")
       cmd="%s %s@%s:%s %s"
       cmd= cmd%(rcopy,userName,hostname,cata_path,resource_dir)
-      print cmd
+      print(cmd)
       os.system(cmd)
 
     schema_cata=os.path.join(resource_dir,"*SchemaCatalog.xml")
@@ -212,7 +212,7 @@ def main():
   options, args = parser.parse_args()
 
   if not os.path.exists(catalog_file_base):
-    print "ERROR: the base catalog file %s is mandatory" % catalog_file_base
+    print("ERROR: the base catalog file %s is mandatory" % catalog_file_base)
     sys.exit(1)
 
   #Parse CatalogResource.xml
@@ -256,7 +256,7 @@ def main():
   doc.write(f)
   f.write('\n')
   f.close()
-  print "%s updated" % catalog_file
+  print("%s updated" % catalog_file)
 
   #update configRemote.sh in env.d directory (environment variable SALOME_CATALOGS_PATH)
   path=[]
index 2ea384b6367a296f9aaa63d6cbf55b74e5289ee0..83111ce7a6946e8708811a2d3c7e05fb394a9b2b 100755 (executable)
@@ -82,9 +82,9 @@ def killAllPorts():
         pass
     # kill other processes
     if sys.platform != 'win32':
-        import commands
+        import subprocess
         cmd = "ps -fea | grep '%s' | grep 'ghs3d' | grep 'f /tmp/GHS3D_' | grep -v 'grep' | awk '{print $2}'" % user
-        prc = commands.getoutput(cmd)
+        prc = subprocess.getoutput(cmd)
         for field in prc.split():
             try:
                 os.kill(int(field), signal.SIGKILL)
@@ -94,7 +94,7 @@ def killAllPorts():
         pass
         # kill ompi-server needed for MPI containers coupling
         cmd = "ps -fea | grep '%s' | grep 'ompi-server' | grep -v 'grep' | awk '{print $2}'" % user
-        prc = commands.getoutput(cmd)
+        prc = subprocess.getoutput(cmd)
         for field in prc.split():
             try:
                 os.kill(int(field), signal.SIGKILL)
@@ -111,8 +111,8 @@ if __name__ == "__main__":
     try:
         from salomeContextUtils import setOmniOrbUserPath
         setOmniOrbUserPath()
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         sys.exit(1)
     killAllPorts()
     pass
index 9670329bf363a9f7e90148632e8d6864a837cc4c..f18052e4120caa998536d6d6b01d3b3f2c75c199 100755 (executable)
@@ -31,7 +31,7 @@
 #  \endcode
 #
 
-import os, sys, pickle, signal, commands,glob
+import os, sys, pickle, signal, subprocess,glob
 import subprocess
 import shlex
 from salome_utils import verbose
@@ -96,7 +96,7 @@ def appliCleanOmniOrbConfig(port):
     the last is removed only if the link points to the first file.
     """
     if verbose():
-        print "clean OmniOrb config for port %s"%port
+        print("clean OmniOrb config for port %s"%port)
 
     from salome_utils import generateFileName, getUserName
     omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
@@ -202,7 +202,7 @@ def shutdownMyPort(port, cleanup=True):
         # shutdown all
         orb = CORBA.ORB_init([''], CORBA.ORB_ID)
         lcc = LifeCycleCORBA(orb) # see (1)
-        print "Terminating SALOME on port %s..."%(port)
+        print("Terminating SALOME on port %s..."%(port))
         lcc.shutdownServers()
         # give some time to shutdown to complete
         time.sleep(1)
@@ -231,19 +231,19 @@ def __killMyPort(port, filedict):
         with open(filedict, 'r') as fpid:
             process_ids=pickle.load(fpid)
             for process_id in process_ids:
-                for pid, cmd in process_id.items():
-                    if verbose(): print "stop process %s : %s"% (pid, cmd[0])
+                for pid, cmd in list(process_id.items()):
+                    if verbose(): print("stop process %s : %s"% (pid, cmd[0]))
                     try:
                         from salome_utils import killpid
                         killpid(int(pid))
                     except:
-                        if verbose(): print "  ------------------ process %s : %s not found"% (pid, cmd[0])
+                        if verbose(): print("  ------------------ process %s : %s not found"% (pid, cmd[0]))
                         pass
                     pass # for pid ...
                 pass # for process_id ...
             # end with
     except:
-        print "Cannot find or open SALOME PIDs file for port", port
+        print("Cannot find or open SALOME PIDs file for port", port)
         pass
     os.remove(filedict)
     pass
@@ -276,7 +276,7 @@ def __guessPiDictFilename(port):
             log_msg += "   ... not found\n"
 
     if verbose():
-        print log_msg
+        print(log_msg)
 
     return filedict
 #
@@ -296,12 +296,12 @@ def killMyPort(port):
         filedict = getPiDict(port)
         if not os.path.isfile(filedict): # removed by previous call, see (1)
             if verbose():
-                print "SALOME on port %s: already removed by previous call"%port
+                print("SALOME on port %s: already removed by previous call"%port)
             # Remove port from PortManager config file
             try:
                 from PortManager import releasePort
                 if verbose():
-                    print "Removing port from PortManager configuration file"
+                    print("Removing port from PortManager configuration file")
                 releasePort(port)
             except ImportError:
                 pass
@@ -391,10 +391,10 @@ def killMyPortSpy(pid, port):
 
 if __name__ == "__main__":
     if len(sys.argv) < 2:
-        print "Usage: "
-        print "  %s <port>" % os.path.basename(sys.argv[0])
-        print
-        print "Kills SALOME session running on specified <port>."
+        print("Usage: ")
+        print("  %s <port>" % os.path.basename(sys.argv[0]))
+        print()
+        print("Kills SALOME session running on specified <port>.")
         sys.exit(1)
         pass
     if sys.argv[1] == "--spy":
@@ -408,8 +408,8 @@ if __name__ == "__main__":
     try:
         from salomeContextUtils import setOmniOrbUserPath #@UnresolvedImport
         setOmniOrbUserPath()
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         sys.exit(1)
     for port in sys.argv[1:]:
         killMyPort(port)
index 57c492797c978a1bb50f293b790b5fdb32688f70..d819dad0f8cf2d4f9613b897ca98ce785c701824 100755 (executable)
@@ -27,6 +27,7 @@ import optparse
 import types
 
 from salome_utils import verbose, getPortNumber, getHomeDir
+from six import string_types
 
 # names of tags in XML configuration file
 doc_tag = "document"
@@ -241,14 +242,14 @@ def userFile(appname, cfgname):
 def process_containers_params( standalone, embedded ):
     # 1. filter inappropriate containers names
     if standalone is not None:
-        standalone = filter( lambda x: x in standalone_choices, standalone )
+        standalone = [x for x in standalone if x in standalone_choices]
     if embedded is not None:
-        embedded   = filter( lambda x: x in embedded_choices,   embedded )
+        embedded   = [x for x in embedded if x in embedded_choices]
 
     # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
     # parameter --> i.e. 'standalone' parameter has higher priority
     if standalone is not None and embedded is not None:
-        embedded = filter( lambda x: x not in standalone, embedded )
+        embedded = [x for x in embedded if x not in standalone]
 
     # 3. return corrected parameters values
     return standalone, embedded
@@ -264,7 +265,7 @@ section_to_skip = ""
 class xml_parser:
     def __init__(self, fileName, _opts, _importHistory):
         #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
-        if verbose(): print "Configure parser: processing %s ..." % fileName
+        if verbose(): print("Configure parser: processing %s ..." % fileName)
         self.fileName = os.path.abspath(fileName)
         self.importHistory = _importHistory
         self.importHistory.append(self.fileName)
@@ -282,12 +283,12 @@ class xml_parser:
             self.opts[ embedded_nam ] = embedded
         pass
 
-    def boolValue( self, str ):
-        strloc = str
-        if isinstance(strloc, types.UnicodeType):
+    def boolValue( self, item):
+        strloc = item
+        if isinstance(strloc, string_types):
             strloc = strloc.encode().strip()
-        if isinstance(strloc, types.StringType):
-            strlow = strloc.lower()
+        if isinstance(strloc, bytes):
+            strlow = strloc.decode().lower()
             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
                 return True
             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
@@ -295,26 +296,29 @@ class xml_parser:
         return strloc
         pass
 
-    def intValue( self, str ):
-        strloc = str
-        if isinstance(strloc, types.UnicodeType):
+    def intValue( self, item):
+        strloc = item
+        if isinstance(strloc, string_types):
             strloc = strloc.encode().strip()
-        if isinstance(strloc, types.StringType):
-            strlow = strloc.lower()
+        if isinstance(strloc, bytes):
+            strlow = strloc.decode().lower()
             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
                 return 1
             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
                 return 0
             else:
-                return string.atoi(strloc)
+                return int(strloc.decode())
         return strloc
         pass
 
-    def strValue( self, str ):
-        strloc = str
+    def strValue( self, item):
+        strloc = item
         try:
-            if isinstance(strloc, types.UnicodeType): strloc = strloc.encode().strip()
-            else: strloc = strloc.strip()
+            if isinstance( strloc, str):
+                strloc = strloc.strip()
+            else:
+                if isinstance( strloc, bytes):
+                    strloc = strloc.decode().strip()
         except:
             pass
         return strloc
@@ -333,7 +337,7 @@ class xml_parser:
             section_name = attrs.getValue( nam_att )
             if section_name in [lanch_nam, lang_nam]:
                 self.section = section_name # launch section
-            elif self.opts.has_key( modules_nam ) and \
+            elif modules_nam in self.opts and \
                  section_name in self.opts[ modules_nam ]:
                 self.section = section_name # <module> section
             else:
@@ -401,12 +405,12 @@ class xml_parser:
             if os.path.exists(absfname + ext) :
                 absfname += ext
                 if absfname in self.importHistory :
-                    if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
+                    if verbose(): print("Configure parser: Warning : file %s is already imported" % absfname)
                     return # already imported
                 break
             pass
         else:
-            if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
+            if verbose(): print("Configure parser: Error : file %s does not exist" % absfname)
             return
 
         # importing file
@@ -417,14 +421,14 @@ class xml_parser:
             # import file
             imp = xml_parser(absfname, opts, self.importHistory)
             # merge results
-            for key in imp.opts.keys():
-                if not self.opts.has_key(key):
+            for key in list(imp.opts.keys()):
+                if key not in self.opts:
                     self.opts[key] = imp.opts[key]
                     pass
                 pass
             pass
         except:
-            if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
+            if verbose(): print("Configure parser: Error : can not read configuration file %s" % absfname)
         pass
 
 
@@ -433,20 +437,20 @@ class xml_parser:
 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
              '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
 
-boolean_choices = booleans.keys()
+boolean_choices = list(booleans.keys())
 
 def check_embedded(option, opt, value, parser):
     from optparse import OptionValueError
     assert value is not None
     if parser.values.embedded:
-        embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
+        embedded = [a for a in re.split( "[:;,]", parser.values.embedded ) if a.strip()]
     else:
         embedded = []
     if parser.values.standalone:
-        standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
+        standalone = [a for a in re.split( "[:;,]", parser.values.standalone ) if a.strip()]
     else:
         standalone = []
-    vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
+    vals = [a for a in re.split( "[:;,]", value ) if a.strip()]
     for v in vals:
         if v not in embedded_choices:
             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
@@ -463,14 +467,14 @@ def check_standalone(option, opt, value, parser):
     from optparse import OptionValueError
     assert value is not None
     if parser.values.embedded:
-        embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
+        embedded = [a for a in re.split( "[:;,]", parser.values.embedded ) if a.strip()]
     else:
         embedded = []
     if parser.values.standalone:
-        standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
+        standalone = [a for a in re.split( "[:;,]", parser.values.standalone ) if a.strip()]
     else:
         standalone = []
-    vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
+    vals = [a for a in re.split( "[:;,]", value ) if a.strip()]
     for v in vals:
         if v not in standalone_choices:
             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
@@ -484,7 +488,7 @@ def check_standalone(option, opt, value, parser):
     pass
 
 def store_boolean (option, opt, value, parser, *args):
-    if isinstance(value, types.StringType):
+    if isinstance(value, bytes):
         try:
             value_conv = booleans[value.strip().lower()]
             for attribute in args:
@@ -894,10 +898,10 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
     # check KERNEL_ROOT_DIR
     kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
     if kernel_root_dir is None:
-        print """
+        print("""
         For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
         KERNEL_ROOT_DIR is mandatory.
-        """
+        """)
         sys.exit(1)
 
     ############################
@@ -910,7 +914,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
     if cmd_opts.print_port:
         from searchFreePort import searchFreePort
         searchFreePort({})
-        print "port:%s"%(os.environ['NSPORT'])
+        print("port:%s"%(os.environ['NSPORT']))
 
         try:
             import PortManager
@@ -956,13 +960,13 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
     for dir in dirs:
         filename = os.path.join(dir, appname+'.xml')
         if not os.path.exists(filename):
-            if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
+            if verbose(): print("Configure parser: Warning : can not find configuration file %s" % filename)
         else:
             try:
                 p = xml_parser(filename, _opts, [])
                 _opts = p.opts
             except:
-                if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
+                if verbose(): print("Configure parser: Error : can not read configuration file %s" % filename)
             pass
 
     # parse user configuration file
@@ -972,15 +976,15 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
     user_config = cmd_opts.resources
     if not user_config:
         user_config = userFile(appname, cfgname)
-        if verbose(): print "Configure parser: user configuration file is", user_config
+        if verbose(): print("Configure parser: user configuration file is", user_config)
     if not user_config or not os.path.exists(user_config):
-        if verbose(): print "Configure parser: Warning : can not find user configuration file"
+        if verbose(): print("Configure parser: Warning : can not find user configuration file")
     else:
         try:
             p = xml_parser(user_config, _opts, [])
             _opts = p.opts
         except:
-            if verbose(): print 'Configure parser: Error : can not read user configuration file'
+            if verbose(): print('Configure parser: Error : can not read user configuration file')
             user_config = ""
 
     args = _opts
@@ -990,11 +994,11 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
 
     # set default values for options which are NOT set in config files
     for aKey in listKeys:
-        if not args.has_key( aKey ):
+        if aKey not in args:
             args[aKey] = []
 
     for aKey in boolKeys:
-        if not args.has_key( aKey ):
+        if aKey not in args:
             args[aKey] = 0
 
     if args[file_nam]:
@@ -1086,11 +1090,11 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
 
     # Embedded
     if cmd_opts.embedded is not None:
-        args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
+        args[embedded_nam] = [a for a in re.split( "[:;,]", cmd_opts.embedded ) if a.strip()]
 
     # Standalone
     if cmd_opts.standalone is not None:
-        args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
+        args[standalone_nam] = [a for a in re.split( "[:;,]", cmd_opts.standalone ) if a.strip()]
 
     # Normalize the '--standalone' and '--embedded' parameters
     standalone, embedded = process_containers_params( args.get( standalone_nam ),
@@ -1202,15 +1206,15 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
     if cmd_opts.use_port is not None:
         min_port = 2810
         max_port = min_port + 100
-        if cmd_opts.use_port not in xrange(min_port, max_port+1):
-            print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
+        if cmd_opts.use_port not in range(min_port, max_port+1):
+            print("Error: port number should be in range [%d, %d])" % (min_port, max_port))
             sys.exit(1)
         args[useport_nam] = cmd_opts.use_port
 
     if cmd_opts.language is not None:
         langs = args["language_languages"] if "language_languages" in args else []
         if cmd_opts.language not in langs:
-            print "Error: unsupported language: %s" % cmd_opts.language
+            print("Error: unsupported language: %s" % cmd_opts.language)
             sys.exit(1)
         args[lang_nam] = cmd_opts.language
 
index f9d1a3a2c6609fc6dfd643360a2aabef71aaa409..5f806971eaf5fabd0889ecc7a4916b2c8ff63f5e 100755 (executable)
@@ -42,11 +42,11 @@ class NamingServer(Server):
         from salome_utils import getLogDir
         upath = getLogDir()
         try:
-            os.makedirs(upath, mode=0777)
+            os.makedirs(upath, mode=0o777)
         except:
             pass
 
-        if verbose(): print "Name Service... ",
+        if verbose(): print("Name Service... ", end=' ')
         #hname=os.environ["HOST"] #commands.getoutput("hostname")
         if sys.platform == "win32":
           hname = getShortHostName();
@@ -56,7 +56,7 @@ class NamingServer(Server):
 
         with open(os.environ["OMNIORB_CONFIG"]) as f:
           ss = re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
-          if verbose(): print "ss = ", ss,
+          if verbose(): print("ss = ", ss, end=' ')
         sl = ss[0]
         ll = sl.split(':')
         aPort = ll[-1]
@@ -97,8 +97,8 @@ class NamingServer(Server):
           self.CMD = ['omniNames','-start' , aPort, '-logdir' , upath, '-errlog', upath+'/omniNameErrors.log']
           #os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
 
-        if verbose(): print "... ok"
-        if verbose(): print "to list contexts and objects bound into the context with the specified name : showNS "
+        if verbose(): print("... ok")
+        if verbose(): print("to list contexts and objects bound into the context with the specified name : showNS ")
 
 
     def initArgs(self):
index 223a91a560880bba9cdb0c60660f034e04b1b25f..81043ac11566d46a66a5dcc09f2c577b1b271d9e 100755 (executable)
@@ -56,7 +56,7 @@ class client:
           return
       except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
           self.rootContext = None
-          if verbose(): print "Launch Naming Service++",
+          if verbose(): print("Launch Naming Service++", end=' ')
 
       # On lance le Naming Server (doit etre dans le PATH)
       test = True
@@ -66,7 +66,7 @@ class client:
       if test:
         NamingServer(args).run()
         pass
-      print "Searching Naming Service ",
+      print("Searching Naming Service ", end=' ')
       ncount=0
       delta=0.1
       while(ncount < 100):
@@ -82,25 +82,25 @@ class client:
               time.sleep(delta)
 
       if self.rootContext is None:
-          print "Failed to narrow the root naming context"
+          print("Failed to narrow the root naming context")
           sys.exit(1)
-      print " found in %s seconds " % ((ncount-1)*delta)
+      print(" found in %s seconds " % ((ncount-1)*delta))
 
     # --------------------------------------------------------------------------
 
     def showNScontext(self,context,dec=''):
       if not context:
-        print "[NS] No context"
+        print("[NS] No context")
         return
       else:
-        print context
+        print(context)
 
       _,bi = context.list(0)
       if bi is not None:
         ok,b = bi.next_one()
         while(ok):
             for s in b.binding_name :
-              print "%s%s.%s" %(dec,s.id,s.kind)
+              print("%s%s.%s" %(dec,s.id,s.kind))
               if s.kind == "dir":
                   obj = context.resolve([s])
                   scontext = obj._narrow(CosNaming.NamingContext)
@@ -116,7 +116,7 @@ class client:
     # --------------------------------------------------------------------------
 
     def Resolve(self, Path):
-      resolve_path = string.split(Path,'/')
+      resolve_path = Path.split('/')
       if resolve_path[0] == '': del resolve_path[0]
       dir_path = resolve_path[:-1]
       context_name = []
@@ -126,11 +126,11 @@ class client:
 
       try:
           obj = self.rootContext.resolve(context_name)
-      except CosNaming.NamingContext.NotFound, ex:
+      except CosNaming.NamingContext.NotFound as ex:
           obj = None
-      except CosNaming.NamingContext.InvalidName, ex:
+      except CosNaming.NamingContext.InvalidName as ex:
           obj = None
-      except CosNaming.NamingContext.CannotProceed, ex:
+      except CosNaming.NamingContext.CannotProceed as ex:
           obj = None
       except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
           obj = None
@@ -141,13 +141,13 @@ class client:
     def waitNS(self,name,typobj=None,maxcount=240):
       count = 0
       delta = 0.5
-      print "Searching %s in Naming Service " % name,
+      print("Searching %s in Naming Service " % name, end=' ')
       while(1):
           count += 1
-          if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name
+          if count > maxcount : raise RuntimeError("Impossible de trouver %s" % name)
           obj = self.Resolve(name)
           if obj :
-              print " found in %s seconds " % ((count-1)*delta)
+              print(" found in %s seconds " % ((count-1)*delta))
               break
           else:
               sys.stdout.write('+')
@@ -158,7 +158,7 @@ class client:
 
       nobj = obj._narrow(typobj)
       if nobj is None:
-            print "%s exists but is not a %s" % (name,typobj)
+            print("%s exists but is not a %s" % (name,typobj))
       return nobj
 
     if sys.platform != "win32":
@@ -166,16 +166,16 @@ class client:
         aCount = 0
         aDelta = 0.5
         anObj = None
-        print "Searching %s in Naming Service " % theName,
+        print("Searching %s in Naming Service " % theName, end=' ')
         while(1):
           try:
             os.kill(thePID,0)
           except:
-            raise RuntimeError, "Process %d for %s not found" % (thePID,theName)
+            raise RuntimeError("Process %d for %s not found" % (thePID,theName))
           aCount += 1
           anObj = self.Resolve(theName)
           if anObj:
-            print " found in %s seconds " % ((aCount-1)*aDelta)
+            print(" found in %s seconds " % ((aCount-1)*aDelta))
             break
           else:
             sys.stdout.write('+')
@@ -189,7 +189,7 @@ class client:
   
         anObject = anObj._narrow(theTypObj)
         if anObject is None:
-          print "%s exists but is not a %s" % (theName,theTypObj)
+          print("%s exists but is not a %s" % (theName,theTypObj))
         return anObject
 
 
@@ -201,11 +201,11 @@ class client:
 
       try:
           obj = self.rootContext.resolve(context_name)
-      except CosNaming.NamingContext.NotFound, ex:
+      except CosNaming.NamingContext.NotFound as ex:
           obj = None
-      except CosNaming.NamingContext.InvalidName, ex:
+      except CosNaming.NamingContext.InvalidName as ex:
           obj = None
-      except CosNaming.NamingContext.CannotProceed, ex:
+      except CosNaming.NamingContext.CannotProceed as ex:
           obj = None
       except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
           obj = None
@@ -216,13 +216,13 @@ class client:
     def waitLogger(self,name,typobj=None,maxcount=40):
       count = 0
       delta = 0.5
-      print "Searching %s in Naming Service " % name,
+      print("Searching %s in Naming Service " % name, end=' ')
       while(1):
           count += 1
-          if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name
+          if count > maxcount : raise RuntimeError("Impossible de trouver %s" % name)
           obj = self.ResolveLogger(name)
           if obj :
-              print " found in %s seconds " % ((count-1)*delta)
+              print(" found in %s seconds " % ((count-1)*delta))
               break
           else:
               sys.stdout.write('+')
@@ -233,5 +233,5 @@ class client:
 
       nobj = obj._narrow(typobj)
       if nobj is None:
-            print "%s exists but is not a %s" % (name,typobj)
+            print("%s exists but is not a %s" % (name,typobj))
       return nobj
index 77e6350df0d426d308535fcb49274ab22456f5fb..63d0c92cc1160b88074288c97cf14f4cf2cf7e62 100644 (file)
@@ -17,7 +17,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import ConfigParser
+import configparser
 import os
 import logging
 import re
@@ -44,9 +44,9 @@ def _expandSystemVariables(key, val):
 #
 
 # :TRICKY: So ugly solution...
-class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
+class MultiOptSafeConfigParser(configparser.SafeConfigParser):
   def __init__(self):
-    ConfigParser.SafeConfigParser.__init__(self)
+    configparser.SafeConfigParser.__init__(self)
 
   # copied from python 2.6.8 Lib.ConfigParser.py
   # modified (see code comments) to handle duplicate keys
@@ -88,7 +88,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
           sectname = mo.group('header')
           if sectname in self._sections:
             cursect = self._sections[sectname]
-          elif sectname == ConfigParser.DEFAULTSECT:
+          elif sectname == configparser.DEFAULTSECT:
             cursect = self._defaults
           else:
             cursect = self._dict()
@@ -98,7 +98,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
           optname = None
         # no section header in the file?
         elif cursect is None:
-          raise ConfigParser.MissingSectionHeaderError(fpname, lineno, line)
+          raise configparser.MissingSectionHeaderError(fpname, lineno, line)
         # an option line?
         else:
           mo = self.OPTCRE.match(line)
@@ -143,7 +143,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
             # raised at the end of the file and will contain a
             # list of all bogus lines
             if not e:
-              e = ConfigParser.ParsingError(fpname)
+              e = configparser.ParsingError(fpname)
             e.append(lineno, repr(line))
     # if any parsing errors occurred, raise an exception
     if e:
@@ -151,9 +151,9 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
 
     # join the multi-line values collected while reading
     all_sections = [self._defaults]
-    all_sections.extend(self._sections.values())
+    all_sections.extend(list(self._sections.values()))
     for options in all_sections:
-      for name, val in options.items():
+      for name, val in list(options.items()):
         if isinstance(val, list):
           options[name] = '\n'.join(val)
   #
@@ -174,13 +174,13 @@ def parseConfigFile(filename, reserved = None):
   # Read config file
   try:
     config.read(filename)
-  except ConfigParser.MissingSectionHeaderError:
+  except configparser.MissingSectionHeaderError:
     logConfigParser.error("No section found in file: %s"%(filename))
     return []
 
   try:
     return __processConfigFile(config, reserved, filename)
-  except ConfigParser.InterpolationMissingOptionError, e:
+  except configparser.InterpolationMissingOptionError as e:
     msg = "A variable may be undefined in SALOME context file: %s\nParser error is: %s\n"%(filename, e)
     raise SalomeContextException(msg)
 #
index bb2192c8695744ba86258f6a8a811d3de23594f5..ee53a2fbf7f48ff33c89de54bde0f67f51d717a6 100644 (file)
@@ -24,7 +24,6 @@
 from optparse import OptionParser
 import os
 import sys
-import user
 import pickle
 
 # Use to display newlines (\n) in epilog
@@ -60,31 +59,31 @@ For example:
                     )
   try:
     (options, args) = parser.parse_args(args)
-  except Exception, e:
-    print e
+  except Exception as e:
+    print(e)
     return
 
   return options, args
 #
 
 def __show_running_instances(list_of_instances):
-  print '-'*10
-  print "Running instances:"
+  print('-'*10)
+  print("Running instances:")
   for i in range(len(list_of_instances)):
     host, port, _ = list_of_instances[i]
-    print "   [%d] %s:%s"%(i+1, host, port)
-  print '-'*10
+    print("   [%d] %s:%s"%(i+1, host, port))
+  print('-'*10)
 #
 
 def __choose_in(choices):
   __show_running_instances(choices)
-  rep = raw_input("Please enter the number of instance to use (0 to cancel): ")
+  rep = input("Please enter the number of instance to use (0 to cancel): ")
   if rep == '0':
     return None, None, None
   elif rep in [str(i) for i in range(1, len(choices)+1)]:
     return choices[int(rep)-1]
   else:
-    print "*** Invalid number! ***"
+    print("*** Invalid number! ***")
     return __choose_in(choices)
 #
 
@@ -102,31 +101,31 @@ def __get_running_session(requested_port=None, lastInstanceByDefault=False):
 
   host, port, filename = None, None, None
   if requested_port:
-    print "Search for running instance on port %s..."%requested_port
+    print("Search for running instance on port %s..."%requested_port)
     found = [(h,p,f) for h,p,f in available_connexions if int(p) == int(requested_port)]
     if not found:
-      print "   ...no running instance found"
+      print("   ...no running instance found")
     elif len(found) == 1:
       host, port, filename = found[0]
-      print "   ...found unique instance: %s:%s"%(host,port)
+      print("   ...found unique instance: %s:%s"%(host,port))
     else:
-      print "   ...multiple instances found ; please choose one in the following:"
+      print("   ...multiple instances found ; please choose one in the following:")
       host, port, filename = __choose_in(found)
   else: # no requested port
     if not available_connexions:
-      print "No running instance found"
+      print("No running instance found")
     elif len(available_connexions) == 1:
       host, port, filename = available_connexions[0]
-      print "Found unique instance: %s:%s"%(host,port)
+      print("Found unique instance: %s:%s"%(host,port))
     else:
-      print "Multiple instances found ; please choose one in the following:"
+      print("Multiple instances found ; please choose one in the following:")
       host, port, filename = __choose_in(available_connexions)
       pass
 
   if port:
-    print "Selected instance: %s:%s"%(host, port)
+    print("Selected instance: %s:%s"%(host, port))
   else:
-    print "Cancel."
+    print("Cancel.")
 
   return host, port, filename
 #
@@ -143,7 +142,7 @@ class client(orbmodule.client):
       self.rootContext = obj._narrow(CosNaming.NamingContext)
       return
     except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
-      print "It's not a valid naming service"
+      print("It's not a valid naming service")
       self.rootContext = None
       sys.stdout.flush()
       raise
@@ -167,7 +166,7 @@ def start_client():
   import salome
   salome.salome_init()
   from salome import lcc
-  print "--> now connected to SALOME"
+  print("--> now connected to SALOME")
 #
 
 def _prompt(environment=None, commands=None, message="Connecting to SALOME"):
@@ -183,10 +182,10 @@ def _prompt(environment=None, commands=None, message="Connecting to SALOME"):
   readline.set_completer(rlcompleter.Completer(environment).complete)
   readline.parse_and_bind("tab: complete")
   # calling this with globals ensures we can see the environment
-  print message
+  print(message)
   shell = code.InteractiveConsole(environment)
   for cmd in commands:
-    print "Execute command:", cmd
+    print("Execute command:", cmd)
     shell.push(cmd)
     pass
   shell.interact()
@@ -208,21 +207,26 @@ def connect(args=None, env=None):
     cmd.append(options.command)
   if args: # unprocessed: may be scripts
     for arg in args:
-      cmd.append("execfile('%s')"%os.path.abspath(os.path.expanduser(arg)))
+      filename = os.path.abspath(os.path.expanduser(arg))
+      pythonLine = "exec(compile(open(%s, \"rb\").read(), %s, 'exec'))"%(filename, filename)
+      cmd.append(pythonLine)
 
   if port:
     import subprocess
     absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
     env_copy = os.environ.copy()
-    proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","runConsole.py"), pickle.dumps(cmd)], shell=False, close_fds=True, env=env_copy)
+    cmdDump=pickle.dumps(cmd,protocol=0)
+    cmdString=cmdDump.decode()
+    proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","runConsole.py"), cmdString], shell=False, close_fds=True, env=env_copy)
     return proc.communicate()
 #
 
 if __name__ == "__main__":
   if len(sys.argv) == 2:
-    cmd = pickle.loads(sys.argv[1])
+    cmdBytes = sys.argv[1].encode()  
+    cmd = pickle.loads(cmdBytes)
     sys.argv = []
     _prompt(commands=cmd)
   else:
-    print "runConsole.py: incorrect usage!"
+    print("runConsole.py: incorrect usage!")
 #
index 33886c27ff6a9717d13b00417071dabbdcffc5d8..6632e530660f62bbedc88509b2e850bef2d49e56 100755 (executable)
@@ -50,7 +50,7 @@ def killLocalPort():
     try:
         killMyPort(my_port)
     except:
-        print "problem in killLocalPort()"
+        print("problem in killLocalPort()")
         pass
     pass
 
@@ -65,7 +65,7 @@ def givenPortKill(port):
     try:
         killMyPort(my_port)
     except:
-        print "problem in LocalPortKill(), killMyPort(%s)"%port
+        print("problem in LocalPortKill(), killMyPort(%s)"%port)
         pass
     pass
 
@@ -101,7 +101,7 @@ class InterpServer(Server):
     def run(self):
         global process_id
         command = self.CMD
-        print "INTERPSERVER::command = ", command
+        print("INTERPSERVER::command = ", command)
         import subprocess
         pid = subprocess.Popen(command).pid
         process_id[pid]=self.CMD
@@ -116,7 +116,7 @@ def get_cata_path(list_modules,modules_root_dir):
     cata_path=[]
 
     for module in list_modules:
-        if modules_root_dir.has_key(module):
+        if module in modules_root_dir:
             module_root_dir=modules_root_dir[module]
             module_cata=module+"Catalog.xml"
             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
@@ -134,7 +134,7 @@ def get_cata_path(list_modules,modules_root_dir):
         if os.path.exists(path):
             for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
                 module_name= os.path.basename(cata_file)[:-11]
-                if not modules_cata.has_key(module_name):
+                if module_name not in modules_cata:
                     cata_path.append(cata_file)
                     modules_cata[module_name]=cata_file
 
@@ -160,7 +160,7 @@ class CatalogServer(Server):
 
         cata_path=get_cata_path(list_modules,modules_root_dir)
 
-        self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+        self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
 
 # ---
 
@@ -207,10 +207,10 @@ class LoggerServer(Server):
                                     with_username=True,
                                     with_hostname=True,
                                     with_port=True)
-        print "==========================================================="
-        print "Logger server: put log to the file:"
-        print logfile
-        print "==========================================================="
+        print("===========================================================")
+        print("Logger server: put log to the file:")
+        print(logfile)
+        print("===========================================================")
         self.CMD=['SALOME_Logger_Server', logfile]
         pass
     pass # end of LoggerServer class
@@ -248,7 +248,7 @@ class SessionServer(Server):
             raise Exception('Python containers no longer supported')
         if self.args['gui']:
             session_gui = True
-            if self.args.has_key('session_gui'):
+            if 'session_gui' in self.args:
                 session_gui = self.args['session_gui']
             if session_gui:
                 self.SCMD2+=['GUI']
@@ -259,7 +259,7 @@ class SessionServer(Server):
                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
                     pass
                 pass
-                if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
+                if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
                     msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
                     self.SCMD2+=['--pyscript=%s'%(msg)]
                     pass
@@ -267,9 +267,9 @@ class SessionServer(Server):
             pass
         if self.args['noexcepthandler']:
             self.SCMD2+=['noexcepthandler']
-        if self.args.has_key('user_config'):
+        if 'user_config' in self.args:
             self.SCMD2+=['--resources=%s'%self.args['user_config']]
-        if self.args.has_key('modules'):
+        if 'modules' in self.args:
             list_modules = []
             #keep only modules with GUI
             for m in modules_list:
@@ -283,7 +283,7 @@ class SessionServer(Server):
             list_modules.reverse()
             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
             pass
-        if self.args.has_key('language'):
+        if 'language' in self.args:
             self.SCMD2+=['--language=%s' % self.args['language']]
         pass
 
@@ -297,14 +297,14 @@ class SessionServer(Server):
 
         cata_path=get_cata_path(list_modules,modules_root_dir)
 
-        if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
+        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
-        if self.args.has_key('test'):
+        if 'test' in self.args:
             self.CMD+=['-test'] + self.args['test']
-        elif self.args.has_key('play'):
+        elif 'play' in self.args:
             self.CMD+=['-play'] + self.args['play']
 
         if self.args["gdb_session"] or self.args["ddd_session"]:
@@ -363,9 +363,9 @@ class LauncherServer(Server):
 
         cata_path=get_cata_path(list_modules,modules_root_dir)
 
-        if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
+        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
 #
@@ -387,12 +387,12 @@ def startSalome(args, modules_list, modules_root_dir):
     """Launch all SALOME servers requested by args"""
     init_time = os.times()
 
-    if verbose(): print "startSalome ", args
+    if verbose(): print("startSalome ", args)
 
     #
     # Set server launch command
     #
-    if args.has_key('server_launch_mode'):
+    if 'server_launch_mode' in args:
         Server.set_server_launch_mode(args['server_launch_mode'])
 
     #
@@ -503,7 +503,7 @@ def startSalome(args, modules_list, modules_root_dir):
 
     #print "ARGS = ",args
     if ('study' not in args['embedded']) | (args["gui"] == 0):
-        print "RunStudy"
+        print("RunStudy")
         myServer=SalomeDSServer(args)
         myServer.run()
         if sys.platform == "win32":
@@ -570,9 +570,9 @@ def startSalome(args, modules_list, modules_root_dir):
           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
         args["session_object"] = session
     end_time = os.times()
-    if verbose(): print
-    print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
-                                                         - init_time[4])
+    if verbose(): print()
+    print("Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
+                                                         - init_time[4]))
 
     # ASV start GUI without Loader
     #if args['gui']:
@@ -589,14 +589,14 @@ def startSalome(args, modules_list, modules_root_dir):
     except:
         import traceback
         traceback.print_exc()
-        print "-------------------------------------------------------------"
-        print "-- to get an external python interpreter:runSalome --interp=1"
-        print "-------------------------------------------------------------"
+        print("-------------------------------------------------------------")
+        print("-- to get an external python interpreter:runSalome --interp=1")
+        print("-------------------------------------------------------------")
 
-    if verbose(): print "additional external python interpreters: ", nbaddi
+    if verbose(): print("additional external python interpreters: ", nbaddi)
     if nbaddi:
         for i in range(nbaddi):
-            print "i=",i
+            print("i=",i)
             anInterp=InterpServer(args)
             anInterp.run()
 
@@ -626,9 +626,9 @@ def useSalome(args, modules_list, modules_root_dir):
     except:
         import traceback
         traceback.print_exc()
-        print
-        print
-        print "--- Error during Salome launch ---"
+        print()
+        print()
+        print("--- Error during Salome launch ---")
 
     #print process_id
 
@@ -636,11 +636,11 @@ def useSalome(args, modules_list, modules_root_dir):
     from killSalomeWithPort import getPiDict
 
     filedict = getPiDict(args['port'])
-    for pid, cmd in process_id.items():
+    for pid, cmd in list(process_id.items()):
         addToKillList(pid, cmd, args['port'])
         pass
 
-    if verbose(): print """
+    if verbose(): print("""
     Saving of the dictionary of Salome processes in %s
     To kill SALOME processes from a console (kill all sessions from all ports):
       python killSalome.py
@@ -652,7 +652,7 @@ def useSalome(args, modules_list, modules_root_dir):
 
     runSalome, with --killall option, starts with killing
     the processes resulting from the previous execution.
-    """%filedict
+    """%filedict)
 
     #
     #  Print Naming Service directory list
@@ -660,8 +660,8 @@ def useSalome(args, modules_list, modules_root_dir):
 
     if clt != None:
         if verbose():
-            print
-            print " --- registered objects tree in Naming Service ---"
+            print()
+            print(" --- registered objects tree in Naming Service ---")
             clt.showNS()
             pass
 
@@ -686,14 +686,14 @@ def useSalome(args, modules_list, modules_root_dir):
 
         # run python scripts, passed as command line arguments
         toimport = []
-        if args.has_key('gui') and args.has_key('session_gui'):
+        if 'gui' in args and 'session_gui' in args:
             if not args['gui'] or not args['session_gui']:
-                if args.has_key('study_hdf'):
+                if 'study_hdf' in args:
                     toopen = args['study_hdf']
                     if toopen:
                         import salome
                         salome.salome_init(toopen)
-                if args.has_key('pyscript'):
+                if 'pyscript' in args:
                     toimport = args['pyscript']
         from salomeContextUtils import formatScriptsAndArgs
         command = formatScriptsAndArgs(toimport)
@@ -706,9 +706,9 @@ def useSalome(args, modules_list, modules_root_dir):
     return clt
 
 def execScript(script_path):
-    print 'executing', script_path
+    print('executing', script_path)
     sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
-    execfile(script_path,globals())
+    exec(compile(open(script_path).read(), script_path, 'exec'),globals())
     del sys.path[0]
 
 # -----------------------------------------------------------------------------
@@ -751,17 +751,17 @@ def main(exeName=None):
     try:
         from salomeContextUtils import setOmniOrbUserPath
         setOmniOrbUserPath()
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         sys.exit(1)
 
     from salome_utils import getHostName
     args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName)
-    print "runSalome running on %s" % getHostName()
+    print("runSalome running on %s" % getHostName())
 
     kill_salome(args)
     save_config = True
-    if args.has_key('save_config'):
+    if 'save_config' in args:
         save_config = args['save_config']
     # --
     test = True
@@ -842,7 +842,6 @@ def foreGround(clt, args):
 #
 
 def runSalome():
-    import user
     clt,args = main()
     # --
     test = args['gui'] and args['session_gui']
index c83ef01a1d4c7e3e3b18dd984d45e5338b90cb62..0c5b568d4daf9c85648d94e881e67965d5fb16e0 100644 (file)
@@ -121,8 +121,8 @@ User "myself" connects to remotemachine to run the script concatenate.py in
   short_args, extra_args = getShortAndExtraArgs(args)
   try:
     (options, args) = parser.parse_args(short_args)
-  except Exception, e:
-    print e
+  except Exception as e:
+    print(e)
     return
 
   port = options.port
@@ -249,7 +249,7 @@ def __copyFiles(user, machine, script, infiles, outfiles):
 
     # copy the infile to the remote server
     cmd = "scp %s %s@%s:%s" % (infile, user, machine, tmp_file)
-    print "[  SCP  ]", cmd
+    print("[  SCP  ]", cmd)
     os.system(cmd)
 
     list_infiles.append(tmp_file)
@@ -273,7 +273,7 @@ def __copyFiles(user, machine, script, infiles, outfiles):
 
   # copy the salome script on the remote server
   cmd = "scp %s %s@%s:%s" % (tmp_script, user, machine, tmp_script)
-  print "[  SCP  ]", cmd
+  print("[  SCP  ]", cmd)
   os.system(cmd)
 
   return list_infiles, list_outfiles, tmp_script
@@ -282,10 +282,10 @@ def __copyFiles(user, machine, script, infiles, outfiles):
 # sa_obj is a ScriptAndArgs object (from salomeContextUtils)
 def __runRemoteSession(sa_obj, params):
   if not params.user:
-    print "ERROR: The user login on remote machine MUST be given."
+    print("ERROR: The user login on remote machine MUST be given.")
     return
   if not params.directory:
-    print "ERROR: The remote directory MUST be given."
+    print("ERROR: The remote directory MUST be given.")
     return
 
   # sa_obj.script may be 'python script.py' --> only process .py file
@@ -299,7 +299,7 @@ def __runRemoteSession(sa_obj, params):
   if params.port:
     command = command + "-p %s "%params.port
   command = command + " %s %s args:%s"%(header, tmp_script, ",".join(tmp_in))
-  print '[  SSH   ] ' + command
+  print('[  SSH   ] ' + command)
   os.system(command)
 
   # Get remote files and clean
@@ -309,12 +309,12 @@ def __runRemoteSession(sa_obj, params):
   for outfile in (sa_obj.out or []):
     remote_outfile = tmp_out.pop(0)
     command = "scp %s@%s:%s %s" %(params.user, params.machine, remote_outfile, outfile)
-    print "[  SCP  ] " + command
+    print("[  SCP  ] " + command)
     os.system(command)
 
   # clean temporary files
   command = "ssh %s@%s \\rm -f %s" % (params.user, params.machine, " ".join(temp_files))
-  print '[  SSH   ] ' + command
+  print('[  SSH   ] ' + command)
   os.system(command)
   os.remove(tmp_script)
 
index 4255abaf08aebfd89d3eb65611c4ea80191c5d3a..a7e8fc0543a2caa0471b86ad6d8e2f3c48ff95fe 100644 (file)
@@ -65,7 +65,7 @@ For complete description of available options, pleaser refer to ctest documentat
     return []
 
   if args[0] in ["-h", "--help"]:
-    print usage + epilog
+    print(usage + epilog)
     sys.exit(0)
 
   return args
index 79cc1ce10272097fc3021f51c289585a2c41b5bc..06277ee22baf02dad5f1601a218e7fb8abea68ac 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (C) 2013-2017  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2013-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
@@ -20,7 +20,7 @@
 import os
 import sys
 import logging
-import ConfigParser
+import configparser
 
 from parseConfigFile import parseConfigFile
 
@@ -68,7 +68,7 @@ Command options:
     any blank characters.
 '''
 
-  print msg
+  print(msg)
 #
 
 """
@@ -101,13 +101,13 @@ class SalomeContext:
   #
 
   def __loadMPI(self, module_name):
-    print "Trying to load MPI module: %s..."%module_name,
+    print("Trying to load MPI module: %s..."%module_name)
     try:
       out, err = subprocess.Popen(["modulecmd", "python", "load", module_name], stdout=subprocess.PIPE).communicate()
-      exec out # define specific environment variables
-      print " OK"
+      exec(out) # define specific environment variables
+      print(" OK")
     except:
-      print " ** Failed **"
+      print(" ** Failed **")
       pass
   #
 
@@ -128,7 +128,9 @@ class SalomeContext:
 
     absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
     env_copy = os.environ.copy()
-    proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), pickle.dumps(self), pickle.dumps(args)], shell=False, close_fds=True, env=env_copy)
+    selfBytes= pickle.dumps(self,protocol=0)
+    argsBytes= pickle.dumps(args,protocol=0)
+    proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), selfBytes.decode(), argsBytes.decode()], shell=False, close_fds=True, env=env_copy)
     out, err = proc.communicate()
     return out, err, proc.returncode
   #
@@ -222,7 +224,7 @@ class SalomeContext:
       'car'     : '_getCar',
       }
 
-    if not command in availableCommands.keys():
+    if not command in list(availableCommands.keys()):
       command = "start"
       options = args
 
@@ -261,16 +263,16 @@ class SalomeContext:
     try:
       res = getattr(self, command)(options) # run appropriate method
       return res or (None, None)
-    except SystemExit, returncode:
+    except SystemExit as returncode:
       if returncode != 0:
-        self.getLogger().error("SystemExit %s in method %s.", returncode, command)
+        self.getLogger().warning("SystemExit %s in method %s.", returncode, command)
       sys.exit(returncode)
-    except StandardError:
+    except Exception:
       self.getLogger().error("Unexpected error:")
       import traceback
       traceback.print_exc()
       sys.exit(1)
-    except SalomeContextException, e:
+    except SalomeContextException as e:
       self.getLogger().error(e)
       sys.exit(1)
   #
@@ -280,7 +282,7 @@ class SalomeContext:
       reserved = []
     try:
       unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
-    except SalomeContextException, e:
+    except SalomeContextException as e:
       msg = "%s"%e
       self.getLogger().error(msg)
       sys.exit(1)
@@ -291,7 +293,7 @@ class SalomeContext:
 
     # set context
     for reserved in reservedDict:
-      a = filter(None, reservedDict[reserved]) # remove empty elements
+      a = [_f for _f in reservedDict[reserved] if _f] # remove empty elements
       a = [ os.path.realpath(x) for x in a ]
       reformattedVals = os.pathsep.join(a)
       if reserved in ["INCLUDE", "LIBPATH"]:
@@ -324,17 +326,17 @@ class SalomeContext:
   def _setContext(self, args=None):
     salome_context_set = os.getenv("SALOME_CONTEXT_SET")
     if salome_context_set:
-      print "***"
-      print "*** SALOME context has already been set."
-      print "*** Enter 'exit' (only once!) to leave SALOME context."
-      print "***"
+      print("***")
+      print("*** SALOME context has already been set.")
+      print("*** Enter 'exit' (only once!) to leave SALOME context.")
+      print("***")
       return
 
     os.environ["SALOME_CONTEXT_SET"] = "yes"
-    print "***"
-    print "*** SALOME context is now set."
-    print "*** Enter 'exit' (only once!) to leave SALOME context."
-    print "***"
+    print("***")
+    print("*** SALOME context is now set.")
+    print("*** Enter 'exit' (only once!) to leave SALOME context.")
+    print("***")
 
     cmd = ["/bin/bash"]
     proc = subprocess.Popen(cmd, shell=False, close_fds=True)
@@ -372,7 +374,7 @@ class SalomeContext:
       args = []
     ports = args
     if not ports:
-      print "Port number(s) not provided to command: salome kill <port(s)>"
+      print("Port number(s) not provided to command: salome kill <port(s)>")
       return
 
     from multiprocessing import Process
@@ -419,7 +421,7 @@ class SalomeContext:
   #
 
   def _showSoftwareVersions(self, softwares=None):
-    config = ConfigParser.SafeConfigParser()
+    config = configparser.SafeConfigParser()
     absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH')
     filename = os.path.join(absoluteAppliPath, "sha1_collections.txt")
     versions = {}
@@ -438,12 +440,12 @@ class SalomeContext:
     if softwares:
       for soft in softwares:
         if versions.has_key(soft.upper()):
-          print soft.upper().rjust(max_len), versions[soft.upper()]
+          print(soft.upper().rjust(max_len), versions[soft.upper()])
     else:
       import collections
       od = collections.OrderedDict(sorted(versions.items()))
       for name, version in od.iteritems():
-        print name.rjust(max_len), versions[name]
+        print(name.rjust(max_len), versions[name])
     pass
 
   def _showInfo(self, args=None):
@@ -465,15 +467,15 @@ Available options are:
       args = ["--version"]
 
     if "-h" in args or "--help" in args:
-      print usage + epilog
+      print(usage + epilog)
       return
 
     if "-p" in args or "--ports" in args:
       import PortManager
       ports = PortManager.getBusyPorts()
-      print "SALOME instances are running on ports:", ports
+      print("SALOME instances are running on ports:", ports)
       if ports:
-        print "Last started instance on port %s"%ports[-1]
+        print("Last started instance on port %s"%ports[-1])
 
     if "-s" in args or "--softwares" in args:
       if "-s" in args:
@@ -486,7 +488,7 @@ Available options are:
       self._showSoftwareVersions(softwares=args[index+1:indexEnd])
 
     if "-v" in args or "--version" in args:
-      print "Running with python", platform.python_version()
+      print("Running with python", platform.python_version())
       self._runAppli(["--version"])
   #
 
@@ -496,7 +498,7 @@ Available options are:
 
     modules = args
     if not modules:
-      print "Module(s) not provided to command: salome doc <module(s)>"
+      print("Module(s) not provided to command: salome doc <module(s)>")
       return
 
     appliPath = os.getenv("ABSOLUTE_APPLI_PATH")
@@ -512,72 +514,72 @@ Available options are:
       if os.path.isfile(docfile):
         out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
       else:
-        print "Online documentation is not accessible for module:", module
+        print("Online documentation is not accessible for module:", module)
 
   def _usage(self, unused=None):
     usage()
   #
 
   def _makeCoffee(self, unused=None):
-    print "                        ("
-    print "                          )     ("
-    print "                   ___...(-------)-....___"
-    print "               .-\"\"       )    (          \"\"-."
-    print "         .-\'``\'|-._             )         _.-|"
-    print "        /  .--.|   `\"\"---...........---\"\"`   |"
-    print "       /  /    |                             |"
-    print "       |  |    |                             |"
-    print "        \\  \\   |                             |"
-    print "         `\\ `\\ |                             |"
-    print "           `\\ `|            SALOME           |"
-    print "           _/ /\\            4 EVER           /"
-    print "          (__/  \\             <3            /"
-    print "       _..---\"\"` \\                         /`\"\"---.._"
-    print "    .-\'           \\                       /          \'-."
-    print "   :               `-.__             __.-\'              :"
-    print "   :                  ) \"\"---...---\"\" (                 :"
-    print "    \'._               `\"--...___...--\"`              _.\'"
-    print "      \\\"\"--..__                              __..--\"\"/"
-    print "       \'._     \"\"\"----.....______.....----\"\"\"     _.\'"
-    print "          `\"\"--..,,_____            _____,,..--\"\"`"
-    print "                        `\"\"\"----\"\"\"`"
-    print ""
-    print "                    SALOME is working for you; what else?"
-    print ""
+    print("                        (")
+    print("                          )     (")
+    print("                   ___...(-------)-....___")
+    print("               .-\"\"       )    (          \"\"-.")
+    print("         .-\'``\'|-._             )         _.-|")
+    print("        /  .--.|   `\"\"---...........---\"\"`   |")
+    print("       /  /    |                             |")
+    print("       |  |    |                             |")
+    print("        \\  \\   |                             |")
+    print("         `\\ `\\ |                             |")
+    print("           `\\ `|            SALOME           |")
+    print("           _/ /\\            4 EVER           /")
+    print("          (__/  \\             <3            /")
+    print("       _..---\"\"` \\                         /`\"\"---.._")
+    print("    .-\'           \\                       /          \'-.")
+    print("   :               `-.__             __.-\'              :")
+    print("   :                  ) \"\"---...---\"\" (                 :")
+    print("    \'._               `\"--...___...--\"`              _.\'")
+    print("      \\\"\"--..__                              __..--\"\"/")
+    print("       \'._     \"\"\"----.....______.....----\"\"\"     _.\'")
+    print("          `\"\"--..,,_____            _____,,..--\"\"`")
+    print("                        `\"\"\"----\"\"\"`")
+    print("")
+    print("                    SALOME is working for you; what else?")
+    print("")
     sys.exit(0)
   #
 
   def _getCar(self, unused=None):
-    print "                                              _____________"
-    print "                                  ..---:::::::-----------. ::::;;."
-    print "                               .\'\"\"\"\"\"\"                  ;;   \\  \":."
-    print "                            .\'\'                          ;     \\   \"\\__."
-    print "                          .\'                            ;;      ;   \\\\\";"
-    print "                        .\'                              ;   _____;   \\\\/"
-    print "                      .\'                               :; ;\"     \\ ___:\'."
-    print "                    .\'--...........................    : =   ____:\"    \\ \\"
-    print "               ..-\"\"                               \"\"\"\'  o\"\"\"     ;     ; :"
-    print "          .--\"\"  .----- ..----...    _.-    --.  ..-\"     ;       ;     ; ;"
-    print "       .\"\"_-     \"--\"\"-----\'\"\"    _-\"        .-\"\"         ;        ;    .-."
-    print "    .\'  .\'   SALOME             .\"         .\"              ;       ;   /. |"
-    print "   /-./\'         4 EVER <3    .\"          /           _..  ;       ;   ;;;|"
-    print "  :  ;-.______               /       _________==.    /_  \\ ;       ;   ;;;;"
-    print "  ;  / |      \"\"\"\"\"\"\"\"\"\"\".---.\"\"\"\"\"\"\"          :    /\" \". |;       ; _; ;;;"
-    print " /\"-/  |                /   /                  /   /     ;|;      ;-\" | ;\';"
-    print ":-  :   \"\"\"----______  /   /              ____.   .  .\"\'. ;;   .-\"..T\"   ."
-    print "\'. \"  ___            \"\":   \'\"\"\"\"\"\"\"\"\"\"\"\"\"\"    .   ; ;    ;; ;.\" .\"   \'--\""
-    print " \",   __ \"\"\"  \"\"---... :- - - - - - - - - \' \'  ; ;  ;    ;;\"  .\""
-    print "  /. ;  \"\"\"---___                             ;  ; ;     ;|.\"\""
-    print " :  \":           \"\"\"----.    .-------.       ;   ; ;     ;:"
-    print "  \\  \'--__               \\   \\        \\     /    | ;     ;;"
-    print "   \'-..   \"\"\"\"---___      :   .______..\\ __/..-\"\"|  ;   ; ;"
-    print "       \"\"--..       \"\"\"--\"        m l s         .   \". . ;"
-    print "             \"\"------...                  ..--\"\"      \" :"
-    print "                        \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"    \\        /"
-    print "                                               \"------\""
-    print ""
-    print "                                Drive your simulation properly with SALOME!"
-    print ""
+    print("                                              _____________")
+    print("                                  ..---:::::::-----------. ::::;;.")
+    print("                               .\'\"\"\"\"\"\"                  ;;   \\  \":.")
+    print("                            .\'\'                          ;     \\   \"\\__.")
+    print("                          .\'                            ;;      ;   \\\\\";")
+    print("                        .\'                              ;   _____;   \\\\/")
+    print("                      .\'                               :; ;\"     \\ ___:\'.")
+    print("                    .\'--...........................    : =   ____:\"    \\ \\")
+    print("               ..-\"\"                               \"\"\"\'  o\"\"\"     ;     ; :")
+    print("          .--\"\"  .----- ..----...    _.-    --.  ..-\"     ;       ;     ; ;")
+    print("       .\"\"_-     \"--\"\"-----\'\"\"    _-\"        .-\"\"         ;        ;    .-.")
+    print("    .\'  .\'   SALOME             .\"         .\"              ;       ;   /. |")
+    print("   /-./\'         4 EVER <3    .\"          /           _..  ;       ;   ;;;|")
+    print("  :  ;-.______               /       _________==.    /_  \\ ;       ;   ;;;;")
+    print("  ;  / |      \"\"\"\"\"\"\"\"\"\"\".---.\"\"\"\"\"\"\"          :    /\" \". |;       ; _; ;;;")
+    print(" /\"-/  |                /   /                  /   /     ;|;      ;-\" | ;\';")
+    print(":-  :   \"\"\"----______  /   /              ____.   .  .\"\'. ;;   .-\"..T\"   .")
+    print("\'. \"  ___            \"\":   \'\"\"\"\"\"\"\"\"\"\"\"\"\"\"    .   ; ;    ;; ;.\" .\"   \'--\"")
+    print(" \",   __ \"\"\"  \"\"---... :- - - - - - - - - \' \'  ; ;  ;    ;;\"  .\"")
+    print("  /. ;  \"\"\"---___                             ;  ; ;     ;|.\"\"")
+    print(" :  \":           \"\"\"----.    .-------.       ;   ; ;     ;:")
+    print("  \\  \'--__               \\   \\        \\     /    | ;     ;;")
+    print("   \'-..   \"\"\"\"---___      :   .______..\\ __/..-\"\"|  ;   ; ;")
+    print("       \"\"--..       \"\"\"--\"        m l s         .   \". . ;")
+    print("             \"\"------...                  ..--\"\"      \" :")
+    print("                        \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"    \\        /")
+    print("                                               \"------\"")
+    print("")
+    print("                                Drive your simulation properly with SALOME!")
+    print("")
     sys.exit(0)
   #
 
@@ -604,8 +606,11 @@ Available options are:
 
 if __name__ == "__main__":
   if len(sys.argv) == 3:
-    context = pickle.loads(sys.argv[1])
-    args = pickle.loads(sys.argv[2])
+    context = sys.argv[1]
+    args = sys.argv[2]
+
+    context = pickle.loads(context.encode())
+    args = pickle.loads(args.encode())
 
     (out, err) = context._startSalome(args)
     if out:
index 7f9151bcfb1bc4d9f0d15e2215f0939d89ead85a..40cd1a225e045bfe94df1f69d5c9e6e36a45f30a 100644 (file)
@@ -188,8 +188,8 @@ def getScriptsAndArgs(args=None, searchPathList=None):
         extracted_args = []
         x = elt.split(",")
         # x is ['[file1', 'file2]', 'val1', 'done', '[1', '2', '3]', '[True', 'False]', 'ok']
-        list_begin_indices = [i for i in xrange(len(x)) if x[i].startswith('[')] # [0, 4, 7]
-        list_end_indices = [i for i in xrange(len(x)) if x[i].endswith(']')] # [1, 6, 8]
+        list_begin_indices = [i for i in range(len(x)) if x[i].startswith('[')] # [0, 4, 7]
+        list_end_indices = [i for i in range(len(x)) if x[i].endswith(']')] # [1, 6, 8]
         start = 0
         for lbeg, lend in zip(list_begin_indices,list_end_indices): # [(0, 1), (4, 6), (7, 8)]
           if lbeg > start:
@@ -255,7 +255,7 @@ def getScriptsAndArgs(args=None, searchPathList=None):
           ispython = False
           try:
             fn = open(currentScript)
-            for i in xrange(10): # read only 10 first lines
+            for i in range(10): # read only 10 first lines
               ln = fn.readline()
               if re.search("#!.*python"):
                 ispython = True
index 52a73fdd058bbe114b4c2c150bd3f72b1914455e..67c352f9902ff905d12bbf78fb38c07083bae56c 100644 (file)
@@ -57,9 +57,9 @@ def _try_bool( arg ):
     If <arg> does not represent a boolean, an exception is raised.
     """
     import types
-    if type( arg ) == types.BooleanType  :
+    if type( arg ) == bool  :
         return arg
-    elif type( arg ) == types.StringType  :
+    elif type( arg ) == bytes  :
         v = str( arg ).lower()
         if   v in [ "yes", "y", "true"  ]: return True
         elif v in [ "no",  "n", "false" ]: return False
@@ -290,7 +290,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None,
     ### check unsupported parameters
     for kw in kwargs:
         if kw not in supported and verbose():
-            print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
+            print('Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw)
             pass
         pass
     ### process supported keywords
@@ -371,7 +371,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None,
 
 # ---
 
-def makeTmpDir( path, mode=0777 ):
+def makeTmpDir( path, mode=0o777 ):
     """
     Make temporary directory with the specified path.
     If the directory exists then clear its contents.
@@ -506,12 +506,12 @@ def killpid(pid, sig = 9):
     if not pid: return
     import os, sys
     if sig != 0:
-        if verbose(): print "######## killpid pid = ", pid
+        if verbose(): print("######## killpid pid = ", pid)
     try:
         if sys.platform == "win32":
             import ctypes
             if sig == 0:
-                # PROCESS_QUERY_INFORMATION (0x0400)   Required to retrieve certain information about a process
+                # PROCESS_QUERY_INFORMATION (0x0400)    Required to retrieve certain information about a process
                 handle = ctypes.windll.kernel32.OpenProcess(0x0400, False, int(pid))
                 if handle: 
                     ret = 1
@@ -519,7 +519,7 @@ def killpid(pid, sig = 9):
                 else:
                     ret = 0
             if sig == 9:
-                # PROCESS_TERMINATE (0x0001)   Required to terminate a process using TerminateProcess.
+                # PROCESS_TERMINATE (0x0001)    Required to terminate a process using TerminateProcess.
                 handle = ctypes.windll.kernel32.OpenProcess(0x0001, False, int(pid))
                 ret = ctypes.windll.kernel32.TerminateProcess(handle, -1)
                 ctypes.windll.kernel32.CloseHandle(handle)
@@ -531,7 +531,7 @@ def killpid(pid, sig = 9):
             ret = 1
             pass
         pass
-    except OSError, e:
+    except OSError as e:
         # errno.ESRCH == 3 is 'No such process'
         if e.errno == 3:
             ret = 0
index cdf304eba8e60a085a5c649bb443b24c57df2fcc..ca2c736ea6396be352a0c5982c614db4e3df4bf0 100755 (executable)
@@ -69,27 +69,27 @@ def searchFreePort_withPortManager(queue, args={}, save_config=1, use_port=None)
   port = getPort(use_port)
 
   if use_port:
-    print "Check if port can be used: %d" % use_port,
+    print("Check if port can be used: %d" % use_port, end=' ')
     if port == use_port and port != -1:
-      print "- OK"
+      print("- OK")
       __setup_config(use_port, args, save_config)
       queue.put([os.environ['OMNIORB_CONFIG'],
                  os.environ['NSPORT'],
                  os.environ['NSHOST']])
       return
     else:
-      print "- KO: port is busy"
+      print("- KO: port is busy")
       pass
   #
-  print "Searching for a free port for naming service:",
+  print("Searching for a free port for naming service:", end=' ')
   if port == -1: # try again
     port = getPort(use_port)
 
   if port != -1:
-    print "%s - OK"%(port)
+    print("%s - OK"%(port))
     __setup_config(port, args, save_config)
   else:
-    print "Unable to obtain port"
+    print("Unable to obtain port")
 
   queue.put([os.environ['OMNIORB_CONFIG'],
              os.environ['NSPORT'],
@@ -99,7 +99,7 @@ def searchFreePort_withPortManager(queue, args={}, save_config=1, use_port=None)
 def __savePortToFile(args):
   # Save Naming service port name into
   # the file args["ns_port_log_file"]
-  if args.has_key('ns_port_log_file'):
+  if 'ns_port_log_file' in args:
     omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
     file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
     with open(file_name, "w") as f:
index 75b6b16e011967c10ce6a6d2410774834559de30..3b973632323145918e33f507b95f3da1ece39d16 100755 (executable)
@@ -121,12 +121,13 @@ class Server:
           pid = os.fork()
           if pid > 0:
             #send real pid to parent
-            os.write(c2pwrite,"%d" % pid)
+            pid_str = "%d" % pid
+            os.write(c2pwrite,pid_str.encode())
             os.close(c2pwrite)
             # exit from second parent
             os._exit(0)
-        except OSError, e:
-          print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
+        except OSError as e:
+          print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
           os.write(c2pwrite,"-1")
           os.close(c2pwrite)
           sys.exit(1)
@@ -136,6 +137,6 @@ class Server:
         os.open("/dev/null", os.O_RDWR)  # redirect standard input (0) to /dev/null
         try:
           os.execvp(args[0], args)
-        except OSError, e:
-          print >>sys.stderr, "(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror)
+        except OSError as e:
+          print("(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror), file=sys.stderr)
           os._exit(127)
index 693a51feb09365dfcd52bab439c2f341c3846b62..0a716c8492f89a19ec6101a9e55e7adfbbf840f8 100755 (executable)
@@ -43,7 +43,7 @@ def add_path(directory, variable_name):
       splitsym = ";"
     else:
       splitsym = ":"
-    if not os.environ.has_key(variable_name):
+    if variable_name not in os.environ:
         os.environ[variable_name] = ""
         pass
     if os.path.exists(directory):
@@ -59,9 +59,8 @@ def add_path(directory, variable_name):
                 if os.path.abspath(_dir) != os.path.abspath(directory):
                   newpath.append(_dir)
             pass
-        import string
         newpath[:0] = [ directory ]
-        newpath = string.join(newpath, splitsym)
+        newpath = splitsym.join(newpath)
         os.environ[variable_name] = newpath
         if variable_name == "PYTHONPATH":
             sys.path[:0] = [os.path.realpath(directory)]
@@ -105,7 +104,7 @@ def get_config(silent=False, exeName=None):
     # and set list of used modules (without KERNEL)
 
     modules_list = []
-    if args.has_key("modules"):
+    if "modules" in args:
         modules_list += args["modules"]
     # KERNEL must be last in the list to locate it at the first place in PATH
     if args["gui"] :
@@ -118,14 +117,14 @@ def get_config(silent=False, exeName=None):
     to_remove_list=[]
     for module in modules_list :
         module_variable=module+"_ROOT_DIR"
-        if not os.environ.has_key(module_variable):
+        if module_variable not in os.environ:
             if not silent:
-                print "*******************************************************"
-                print "*"
-                print "* Environment variable",module_variable,"must be set"
-                print "* Module", module, "will be not available"
-                print "*"
-                print "********************************************************"
+                print("*******************************************************")
+                print("*")
+                print("* Environment variable",module_variable,"must be set")
+                print("* Module", module, "will be not available")
+                print("*")
+                print("********************************************************")
                 pass
             to_remove_list.append(module)
             continue
@@ -170,7 +169,7 @@ def set_env(args, modules_list, modules_root_dir, silent=False):
         modules_list = modules_list[:] + ["GUI"]
     modules_list = modules_list[:] + ["KERNEL"]
     for module in modules_list :
-        if modules_root_dir.has_key(module):
+        if module in modules_root_dir:
             module_root_dir = modules_root_dir[module]
             if module_root_dir not in modules_root_dir_list:
               modules_root_dir_list[:0] = [module_root_dir]
@@ -230,10 +229,10 @@ def set_env(args, modules_list, modules_root_dir, silent=False):
 
     # set trace environment variable
 
-    if not os.environ.has_key("SALOME_trace"):
+    if "SALOME_trace" not in os.environ:
         os.environ["SALOME_trace"]="local"
     if args['file']:
-        os.environ["SALOME_trace"]="file:"+args['file'][0]
+        os.environ["SALOME_trace"]="file:"+args['file'][0].decode()
     if args['logger']:
         os.environ["SALOME_trace"]="with_logger"
 
index 3d7fbc0f9ab5120aaf99f2c3acfa53d7ee869f79..1be8dbf8e71b9338ac85049b7f3f56073390b771 100755 (executable)
@@ -1,4 +1,4 @@
-#  -*- coding: iso-8859-1 -*-
+#  i*- coding: iso-8859-1 -*-
 # Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 #
 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
@@ -43,11 +43,11 @@ def mkdir(path):
     """Create a directory and all the intermediate directories if path does not exist"""
     if not os.path.exists(path):
         if verbose:
-            print 'Creating %s' % path
+            print('Creating %s' % path)
         os.makedirs(path)
     else:
         if verbose:
-            print 'Directory %s already exists' % path
+            print('Directory %s already exists' % path)
             pass
         pass
 
@@ -57,15 +57,15 @@ def symlink(src, dest):
     """Create a link if it does not exist"""
     if not os.path.exists(dest):
         if os.path.lexists(dest):
-            print "Do not create symlink %s. It already exists but it's broken" % dest
+            print("Do not create symlink %s. It already exists but it's broken" % dest)
             return
         if verbose:
-            print 'Creating symlink %s' % dest
+            print('Creating symlink %s' % dest)
             pass
         os.symlink(src, dest)
     else:
         if verbose:
-            print 'Symlink %s already exists' % dest
+            print('Symlink %s already exists' % dest)
         pass
     pass
 
@@ -74,11 +74,11 @@ def symlink(src, dest):
 def rmtree(dir):
     """Remove (recursive) a directory if it exists"""
     if os.path.exists(dir):
-        print 'Deleting tree %s' % dir
+        print('Deleting tree %s' % dir)
         shutil.rmtree(dir)
     else:
         if verbose:
-            print 'Do not need to delete %s; already gone' % dir
+            print('Do not need to delete %s; already gone' % dir)
             pass
         pass
     pass
@@ -99,12 +99,12 @@ def link_module(options):
     global verbose
 
     if not options.module_path:
-        print "Option module is mandatory"
+        print("Option module is mandatory")
         return
 
     module_dir=os.path.abspath(options.module_path)
     if not os.path.exists(module_dir):
-        print "Module %s does not exist" % module_dir
+        print("Module %s does not exist" % module_dir)
         return
 
     verbose = options.verbose
@@ -127,7 +127,7 @@ def link_module(options):
       pyversio=versio
     else:
       #incompatible python versions
-      print "incompatible python versions : application has version %s and module %s has not" % (versio,module_dir)
+      print("incompatible python versions : application has version %s and module %s has not" % (versio,module_dir))
       return
 
     module_bin_dir=os.path.join(module_dir,'bin','salome')
@@ -188,20 +188,21 @@ def link_module(options):
         pass
     else:
         if verbose:
-            print module_bin_dir, " doesn't exist"
+            print(module_bin_dir, " doesn't exist")
         pass
 
     #directory bin/salome/test : create it and link content
     if os.path.exists(module_test_dir):
         # link <appli_path>/bin/salome/test/<module> to <module_path>/bin/salome/test
-        print "link %s --> %s"%(os.path.join(test_dir, options.module_name), module_test_dir)
+        print("link %s --> %s"%(os.path.join(test_dir, options.module_name), module_test_dir))
         symlink(module_test_dir, os.path.join(test_dir, options.module_name))
         # register module for testing in CTestTestfile.cmake
         with open(os.path.join(test_dir, "CTestTestfile.cmake"), "ab") as f:
-            f.write("SUBDIRS(%s)\n"%options.module_name)
+            aStr = "SUBDIRS(%s)\n"%options.module_name
+            f.write(aStr.encode())
     else:
         if verbose:
-            print module_test_dir, " doesn't exist"
+            print(module_test_dir, " doesn't exist")
         pass
 
     #directory idl/salome : create it and link content
@@ -211,7 +212,7 @@ def link_module(options):
             symlink(os.path.join(module_idl_dir, fn), os.path.join(idl_dir, fn))
     else:
         if verbose:
-            print module_idl_dir, " doesn't exist"
+            print(module_idl_dir, " doesn't exist")
 
     #directory lib/salome : create it and link content
     if os.path.exists(module_lib_dir):
@@ -222,7 +223,7 @@ def link_module(options):
         pass
     else:
         if verbose:
-            print module_lib_dir, " doesn't exist"
+            print(module_lib_dir, " doesn't exist")
         pass
 
     #directory lib/paraview : create it and link content
@@ -234,12 +235,12 @@ def link_module(options):
         pass
     else:
         if verbose:
-            print module_pvlib_dir, " doesn't exist"
+            print(module_pvlib_dir, " doesn't exist")
         pass
 
     #directory lib/pyversio/site-packages/salome : create it and link content
     if not os.path.exists(module_lib_py_dir):
-        print "Python directory %s does not exist" % module_lib_py_dir
+        print("Python directory %s does not exist" % module_lib_py_dir)
     else:
         # Specific action for the package salome
         module_lib_pypkg_dir=os.path.join(module_lib_py_dir,"salome")
@@ -262,7 +263,7 @@ def link_module(options):
             pass
         else:
             if verbose:
-                print module_lib_py_shared_dir, " doesn't exist"
+                print(module_lib_py_shared_dir, " doesn't exist")
             pass
 
     #directory share/doc/salome (KERNEL doc) : create it and link content
@@ -322,7 +323,7 @@ def link_module(options):
                 #other directories (not resources)
                 symlink(os.path.join(module_share_dir, fn), os.path.join(share_dir, fn))
     else:
-        print "share/salome directory %s does not exist" % module_share_dir
+        print("share/salome directory %s does not exist" % module_share_dir)
         pass
 
     #html files in doc/salome directory
@@ -355,12 +356,12 @@ def link_extra_test(options):
     global verbose
 
     if not options.extra_test_path:
-        print "Option extra_test is mandatory"
+        print("Option extra_test is mandatory")
         return
 
     extra_test_dir=os.path.abspath(options.extra_test_path)
     if not os.path.exists(extra_test_dir):
-        print "Test %s does not exist" % extra_test_dir
+        print("Test %s does not exist" % extra_test_dir)
         return
 
     verbose = options.verbose
@@ -375,14 +376,14 @@ def link_extra_test(options):
     #directory bin/salome/test : create it and link content
     if os.path.exists(extra_test_dir):
         # link <appli_path>/bin/salome/test/<extra_test> to <extra_test_path>/bin/salome/test
-        print "link %s --> %s"%(os.path.join(test_dir, options.extra_test_name), extra_test_dir)
+        print("link %s --> %s"%(os.path.join(test_dir, options.extra_test_name), extra_test_dir))
         symlink(extra_test_dir, os.path.join(test_dir, options.extra_test_name))
         # register extra_test for testing in CTestTestfile.cmake
         with open(os.path.join(test_dir, "CTestTestfile.cmake"), "ab") as f:
             f.write("SUBDIRS(%s)\n"%options.extra_test_name)
     else:
         if verbose:
-            print extra_test_dir, " doesn't exist"
+            print(extra_test_dir, " doesn't exist")
         pass
 
 # -----------------------------------------------------------------------------
index 6bc37fa433a18ce43a5bfaf8108e35ce11261b52..e8bf94acf7e9755afc5aab508ccef1d70b91ced0 100755 (executable)
@@ -43,11 +43,11 @@ while(1):
   try:
     ccontext = rootContext.resolve(cname)
     break
-  except CosNaming.NamingContext.NotFound, ex:
+  except CosNaming.NamingContext.NotFound as ex:
     time.sleep(1)
-  except CosNaming.NamingContext.InvalidName, ex:
+  except CosNaming.NamingContext.InvalidName as ex:
     time.sleep(1)
-  except CosNaming.NamingContext.CannotProceed, ex:
+  except CosNaming.NamingContext.CannotProceed as ex:
     time.sleep(1)
   except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
     time.sleep(1)
@@ -68,7 +68,7 @@ def waitContainer(mycont):
               while(ok):
                 for s in bb.binding_name :
                    if s.id == mycont:
-                     print s.id
+                     print(s.id)
                      return
                 ok,bb=bii.next_one()
         ok,b=bi.next_one()
index 4f9439e83daa4eeec4256367bc5136e8060b8816..cb665591f0576fc42f0e06edc5bc42b2468f8a58 100644 (file)
@@ -337,7 +337,7 @@ def tok_eater(type, tok, spos, epos, line):
                     s = 'static '
                     if params[0] == 'cls':
                         param = string.join(params[1:], ",")
-               s = s+name+"("+param+");\n"
+                s = s+name+"("+param+");\n"
                 if len(name) > 1 \
                    and name[0:2] == '__' \
                    and name[len(name)-2:len(name)] != '__' \
@@ -345,7 +345,7 @@ def tok_eater(type, tok, spos, epos, line):
                        private_member = True
                        output("  private:\n",(def_spos[0]+2,def_spos[1]))
             else:
-               s = name+"("+param+");\n"
+                s = name+"("+param+");\n"
             if (doc_string!=""): comment_block.append(doc_string)
             print_comment(def_spos)
             output(s,def_spos)
@@ -427,12 +427,12 @@ def filterFile(filename, out=sys.stdout):
         root,ext  = os.path.splitext(filename)
 
         if ext==".py":
-            filter(filename)
+            list(filter(filename))
         else:
             dump(filename)
 
         sys.stderr.write("OK\n")
-    except IOError,e:
+    except IOError as e:
         sys.stderr.write(e[1]+"\n")
 
 
@@ -478,7 +478,7 @@ def convert(srcpath, destpath):
          namespace=namespace+"::"+os.path.split(srcpath)[1]
        else:
          namespace=os.path.split(srcpath)[1]
-       print "It's a package:",namespace
+       print("It's a package:",namespace)
     sp = os.path.join(srcpath,"*")
     sfiles = glob.glob(sp)
     dp = os.path.join(destpath,"*")
@@ -507,7 +507,7 @@ def convert(srcpath, destpath):
 
         destfile = os.path.join(destpath,basename)
         if destfile==srcfile:
-            print "WARNING: Input and output names are identical!"
+            print("WARNING: Input and output names are identical!")
             sys.exit(1)
 
         count+=1
@@ -527,12 +527,12 @@ def convert(srcpath, destpath):
             try:
                 shutil.rmtree(dname)
             except:
-                print "Can't remove obsolete directory '%s'"%dname
+                print("Can't remove obsolete directory '%s'"%dname)
         else:
             try:
                 os.remove(dname)
             except:
-                print "Can't remove obsolete file '%s'"%dname
+                print("Can't remove obsolete file '%s'"%dname)
 
     return count
 
@@ -545,8 +545,8 @@ filter_file = False
 
 try:
     opts, args = getopt.getopt(sys.argv[1:], "hf", ["help"])
-except getopt.GetoptError,e:
-    print e
+except getopt.GetoptError as e:
+    print(e)
     sys.exit(1)
 
 for o,a in opts:
@@ -564,6 +564,6 @@ else:
         sys.exit(1)
 
     # Filter an entire Python source tree
-    print '"%s" -> "%s"\n'%(args[0],args[1])
+    print('"%s" -> "%s"\n'%(args[0],args[1]))
     c=convert(args[0],args[1])
-    print "%d files"%(c)
+    print("%d files"%(c))
index dbe0153e75ef44f2336b684e9224c4b91d699d12..b818d7af747dfddd1b87dbeaaedb58d36abf3537 100755 (executable)
@@ -65,8 +65,8 @@ def main(input_file, output_file = None):
 
     for line in infile.readlines():
         # 1. remove comments like """some_comments"""
-        n = line.find('"""')
-        n1 = line[(n+2):].find('"""')
+        n = line.find(b'"""')
+        n1 = line[(n+2):].find(b'"""')
         if (n > -1) and (n1 > -1):
             continue
         if isCom:
index 59cefd2d432ae10a89b8969415af848cc96da25b..77eaaff34ca867df5f8b300ed584076dceb49dbe 100755 (executable)
@@ -85,8 +85,8 @@ def profileGenerateSplash( resources_dir, appname, version, subtext ):
     import ImageDraw
     import ImageFont
 
-    uname = unicode(appname, 'UTF-8')
-    uversion = unicode(version, 'UTF-8')
+    uname = str(appname, 'UTF-8')
+    uversion = str(version, 'UTF-8')
 
     # fonts
     fontbig = ImageFont.truetype( os.path.join( resources_dir, 'Anita semi square.ttf' ), 64)
@@ -143,7 +143,7 @@ def profileGenerateLogo( appname, font ):
     import Image
     import ImageDraw
 
-    uname = unicode(appname, 'UTF-8')
+    uname = str(appname, 'UTF-8')
 
     # evaluate size before deleting draw
     im = Image.new( "RGBA", (1, 1), (0, 0, 0, 0) )
@@ -188,8 +188,8 @@ def profileGenerateSources( options, args ) :
     #Check if the directory of the sources already exists and delete it
     if os.path.exists( app_dir ) :
         if not options.force :
-            print "Directory %s already exists." %app_dir
-            print "Use option --force to overwrite it."
+            print("Directory %s already exists." %app_dir)
+            print("Use option --force to overwrite it.")
             return
         else :
             shutil.rmtree( app_dir )
@@ -249,7 +249,7 @@ def profileGenerateSources( options, args ) :
             shutil.copy( about_name, splash_destination )
 
     #End of script
-    print "Sources of %s were generated in %s." %( options.name, app_dir )
+    print("Sources of %s were generated in %s." %( options.name, app_dir ))
 
 
 # -----------------------------------------------------------------------------
index 62c813abcbc147727dbdaabd8a2a6d2315898fae..44159b3954c15250affceed3e0a6cfb2e39f8bc8 100644 (file)
@@ -1 +1 @@
-print "Hello world"
+print("Hello world")
index b681a0124fcf7595b4e1eadab09e5016772a86c7..4537accaa115f38ddda619f261096e55256f8025 100644 (file)
@@ -601,7 +601,7 @@ Engines_Container_i::load_component_PythonImplementation(const char* componentNa
                                          (char*)"import_component",
                                          (char*)"s",componentName);
 
-  reason=PyString_AsString(result);
+  reason=PyUnicode_AsUTF8(result);
   Py_XDECREF(result);
   SCRUTE(reason);
   PyGILState_Release(gstate);
@@ -1691,9 +1691,9 @@ Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, cons
         es.text = "can not create a python node";
         throw SALOME::SALOME_Exception(es);
       }
-    long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
+    long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
     PyObject* result=PyTuple_GetItem(res,1);
-    std::string astr=PyString_AsString(result);
+    std::string astr=PyUnicode_AsUTF8(result);
     Py_DECREF(res);
     PyGILState_Release(gstate);
     if(ierr==0)
@@ -1774,9 +1774,9 @@ Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* no
         es.text = "can not create a python node";
         throw SALOME::SALOME_Exception(es);
       }
-    long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
+    long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
     PyObject* result=PyTuple_GetItem(res,1);
-    std::string astr=PyString_AsString(result);
+    std::string astr=PyUnicode_AsUTF8(result);
     Py_DECREF(res);
     PyGILState_Release(gstate);
 
@@ -1916,3 +1916,43 @@ void Engines_Container_i::clearTemporaryFiles()
   }
   _tmp_files.clear();
 }
+
+/*
+std::string Engines_Container_i::AnotherMethodeToReplace_PyString_AsString(PyObject * result)
+{
+    std::string my_result = "";
+    if (PyUnicode_Check(result)) {
+        // Convert string to bytes.
+        // strdup() bytes into my_result.
+        PyObject * temp_bytes = PyUnicode_AsEncodedString(result, "ASCII", "strict"); // Owned reference
+        if (temp_bytes != NULL) {
+            my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
+            my_result = strdup(my_result);
+            Py_DECREF(temp_bytes);
+        } else {
+            // TODO PY3: Handle encoding error.
+            Py_DECREF(temp_bytes);
+        }
+
+    } else if (PyBytes_Check(result)) {
+        // strdup() bytes into my_result.
+        my_result = PyBytes_AS_STRING(result); // Borrowed pointer
+        my_result = strdup(my_result);
+    } else {
+        // Convert into your favorite string representation.
+        // Convert string to bytes if it is not already.
+        // strdup() bytes into my_result.
+        // TODO PY3: Check if only bytes is ok. 
+        PyObject * temp_bytes = PyObject_Bytes(result); // Owned reference
+        if (temp_bytes != NULL) {
+            my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
+            my_result = strdup(my_result);
+            Py_DECREF(temp_bytes);
+        } else {
+            // TODO PY3: Handle error.
+            Py_DECREF(temp_bytes);
+        }
+    }
+    return my_result;
+}
+*/
index dad0be21b03f3fe07fbd07f1c996baa62304b875..42ab6eaac4da809830ff83bc05fbf21bd7510f63 100644 (file)
@@ -41,11 +41,25 @@ void KERNEL_PYTHON::init_python(int argc, char **argv)
   MESSAGE("=================================================================");
   // set stdout to line buffering (aka C++ std::cout)
   setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
-  char* salome_python=getenv("SALOME_PYTHON");
-  if(salome_python != 0)
-    Py_SetProgramName(salome_python);
+  wchar_t* salome_python;
+  char* env_python=getenv("SALOME_PYTHON");
+  if(env_python != 0)
+    {
+      wchar_t* salome_python = Py_DecodeLocale(env_python, NULL);
+      Py_SetProgramName(salome_python);
+    }
   Py_Initialize(); // Initialize the interpreter
-  PySys_SetArgv(argc, argv);
+  if (Py_IsInitialized())
+    {
+      MESSAGE("Python initialized eh eh eh");
+    }
+  wchar_t **changed_argv = new wchar_t*[argc]; // Setting arguments
+  for (int i = 0; i < argc; i++)
+  {
+    changed_argv[i] = Py_DecodeLocale(argv[i], NULL);
+  }
+  PySys_SetArgv(argc, changed_argv);
+
   PyRun_SimpleString("import threading\n");
   // VSR (22/09/2016): This is a workaround to prevent invoking qFatal() from PyQt5
   // causing application aborting
@@ -62,6 +76,7 @@ void KERNEL_PYTHON::init_python(int argc, char **argv)
   // VSR (22/09/2016): end of workaround
   PyEval_InitThreads(); // Create (and acquire) the interpreter lock
   PyThreadState *pts = PyGILState_GetThisThreadState(); 
-  PyEval_ReleaseThread(pts);  
+  PyEval_ReleaseThread(pts);
+  //delete[] changed_argv;
 }
 
index a9ce718b870a11f2d5f3b6814189089cbd1ba2e1..90daef95e041203adc022bb7d5e7dd697a21e20b 100755 (executable)
@@ -46,7 +46,7 @@ from libNOTIFICATION import *
 
 from SALOME_utilities import *
 
-from thread import *
+from _thread import *
 
 #=============================================================================
 
@@ -173,7 +173,7 @@ class SALOME_ComponentPy_i (Engines__POA.EngineComponent):
         self._StartUsed = self.CpuUsed_impl()
         self._ThreadCpuUsed = 0
         self._Executed = 1
-        print "beginService for ",serviceName," Component instance : ",self._instanceName
+        print("beginService for ",serviceName," Component instance : ",self._instanceName)
         MESSAGE( "SALOME_ComponentPy_i::beginService _StartUsed " + str( self._ThreadId ) + " " + str( self._StartUsed ) )
         for e in self._fieldsDict:
           key=e.key
@@ -187,7 +187,7 @@ class SALOME_ComponentPy_i (Engines__POA.EngineComponent):
     def endService(self , serviceName ):
         MESSAGE(  "Send EndService notification for " + str( self._ThreadId ) + " " + str(serviceName) + " for graph/node " + str(self._graphName) + " " + str(self._nodeName) + " CpuUsed " + str( self.CpuUsed_impl() ) )
         MESSAGE(  "Component instance : " + str(self._instanceName) )
-        print "endService for",serviceName,"Component instance :",self._instanceName,"Cpu Used:",self.CpuUsed_impl()," (s) "
+        print("endService for",serviceName,"Component instance :",self._instanceName,"Cpu Used:",self.CpuUsed_impl()," (s) ")
 
 
     #-------------------------------------------------------------------------
index 2d6ee3b7588f15998aa6cef29e87a6ad9bcccd4b..25860089df0ccd45978c0edc77a44aac7a19e9a6 100644 (file)
@@ -65,7 +65,7 @@ class SALOME_Container_i:
         self._orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
         self._poa = self._orb.resolve_initial_references("RootPOA")
         self._containerName = containerName
-        if verbose(): print "SALOME_Container.SALOME_Container_i : _containerName ",self._containerName
+        if verbose(): print("SALOME_Container.SALOME_Container_i : _containerName ",self._containerName)
         #self._naming_service = SALOME_NamingServicePy_i(self._orb)
         self._container = self._orb.string_to_object(containerIORStr)
 
@@ -75,10 +75,10 @@ class SALOME_Container_i:
         MESSAGE( "SALOME_Container_i::import_component" )
         ret=""
         try:
-            if verbose(): print "try import ",componentName
+            if verbose(): print("try import ",componentName)
             __import__(componentName)
-            if verbose(): print "import ",componentName," successful"
-        except ImportError,e:
+            if verbose(): print("import ",componentName," successful")
+        except ImportError as e:
             #can't import python module componentName
             #try to find it in python path
             try:
@@ -87,17 +87,17 @@ class SALOME_Container_i:
               #module file found in path
               ret="Component "+componentName+": Python implementation found but it can't be loaded\n"
               ret=ret+traceback.format_exc(10)
-            except ImportError,ee:
+            except ImportError as ee:
               ret="ImplementationNotFound"
             except:
-              if verbose():print "error when calling find_module"
+              if verbose():print("error when calling find_module")
               ret="ImplementationNotFound"
         except:
             ret="Component "+componentName+": Python implementation found but it can't be loaded\n"
             ret=ret+traceback.format_exc(10)
             if verbose():
               traceback.print_exc()
-              print "import ",componentName," not possible"
+              print("import ",componentName," not possible")
         return ret
         
     #-------------------------------------------------------------------------
index 4da4bacad72a5bc514c529ade61c08aa1dce5a1b..a9cce39d04faee5e805c0524fd9c223afd5cb33a 100755 (executable)
@@ -61,7 +61,7 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
         myMachine=getShortHostName()
         Container_path = "/Containers/" + myMachine + "/" + containerName
         self._containerName = Container_path
-        if verbose(): print "container name ",self._containerName
+        if verbose(): print("container name ",self._containerName)
 
         naming_service = SALOME_NamingServicePy_i(self._orb)
         self._naming_service = naming_service
@@ -138,7 +138,7 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
     def instance(self, nameToRegister, componentName):
         MESSAGE(  "SALOME_ContainerPy_i::instance " + str(nameToRegister) + ' ' + str(componentName) )
         self._numInstance = self._numInstance +1
-        instanceName = nameToRegister + "_inst_" + `self._numInstance`
+        instanceName = nameToRegister + "_inst_" + repr(self._numInstance)
 
         component=__import__(componentName)
         factory=getattr(component,componentName)
@@ -154,13 +154,13 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
     def load_impl(self, nameToRegister, componentName):
         MESSAGE(  "SALOME_ContainerPy_i::load_impl " + str(nameToRegister) + ' ' + str(componentName) )
         self._numInstance = self._numInstance +1
-        instanceName = nameToRegister + "_inst_" + `self._numInstance`
+        instanceName = nameToRegister + "_inst_" + repr(self._numInstance)
         interfaceName = nameToRegister
         the_command = "import " + nameToRegister + "\n"
         the_command = the_command + "comp_i = " + nameToRegister + "." + nameToRegister
         the_command = the_command + "(self._orb, self._poa, self._this(), self._containerName, instanceName, interfaceName)\n"
         MESSAGE( "SALOME_ContainerPy_i::load_impl :" + str (the_command) )
-        exec the_command
+        exec(the_command)
         comp_o = comp_i._this()
         return comp_o
     
@@ -170,19 +170,19 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
         MESSAGE( "SALOME_Container_i::import_component" )
         reason = ""
         try:
-            if verbose(): print "try import %s" % componentName
+            if verbose(): print("try import %s" % componentName)
             # try import component
             module=__import__(componentName)
-            if verbose(): print "import %s is done successfully" % componentName
+            if verbose(): print("import %s is done successfully" % componentName)
             # if import successfully, check that component is loadable
             if not hasattr(module, componentName):
                 reason = "module %s is not loadable" % componentName
-                print reason
+                print(reason)
                 pass
             pass
         except:
             import traceback
-            print "cannot import %s" % componentName
+            print("cannot import %s" % componentName)
             traceback.print_exc()
             reason = "cannot import %s" % componentName
         return reason
@@ -192,7 +192,7 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
     def load_component_Library(self, componentName):
         MESSAGE(  "SALOME_ContainerPy_i::load_component_Library " + str(componentName) )
         ret = 0
-        instanceName = componentName + "_inst_" + `self._numInstance`
+        instanceName = componentName + "_inst_" + repr(self._numInstance)
         interfaceName = componentName
         reason = self.import_component(componentName)
         return reason == "", reason
@@ -209,7 +209,7 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
             return None
         else:
             self._numInstance = self._numInstance +1
-            instanceName = componentName + "_inst_" + `self._numInstance`
+            instanceName = componentName + "_inst_" + repr(self._numInstance)
             comp_iors=""
             try:
                 component=__import__(componentName)
@@ -234,7 +234,7 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
 
     def find_component_instance(self, registeredName, studyId):
         anEngine = None
-        keysList = self._listInstances_map.keys()
+        keysList = list(self._listInstances_map.keys())
         i = 0
         while i < len(keysList):
             instance = keysList[i]
@@ -319,19 +319,19 @@ if __name__ == "__main__":
   # change the stdout buffering to line buffering (same as C++ cout buffering)
   sys.stdout=os.fdopen(1,"w",1)
   #initialise the ORB and find the root POA
-  if verbose():print "Starting ",sys.argv[1]
+  if verbose():print("Starting ",sys.argv[1])
   orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
   poa = orb.resolve_initial_references("RootPOA")
-  if verbose():print "ORB and POA initialized"
+  if verbose():print("ORB and POA initialized")
 
   #create an instance of SALOME_ContainerPy_i and a Container reference
   #containerName = "FactoryServerPy"
   MESSAGE( str(sys.argv) )
   containerName = sys.argv[1]
   cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
-  if verbose():print "SALOME_ContainerPy_i instance created ",cpy_i 
+  if verbose():print("SALOME_ContainerPy_i instance created ",cpy_i) 
   cpy_o = cpy_i._this()
-  if verbose():print "SALOME_ContainerPy_i instance activated ",cpy_o
+  if verbose():print("SALOME_ContainerPy_i instance activated ",cpy_o)
   sys.stdout.flush()
   sys.stderr.flush()
 
@@ -341,4 +341,4 @@ if __name__ == "__main__":
 
   #Block for ever
   orb.run()
-  if verbose():print "SALOME_ContainerPy_i shutdown"
+  if verbose():print("SALOME_ContainerPy_i shutdown")
index 2feb5d4c9ceb0ddd0efbd4c131d64df39a767c1c..62cf5906f786f83e839d10441215bcf69b2f7f87 100644 (file)
@@ -26,7 +26,7 @@
 #
 import sys,traceback,string
 import linecache
-import cPickle
+import pickle
 import Engines__POA
 import SALOME__POA
 import SALOME
@@ -47,7 +47,7 @@ class Generic(SALOME__POA.GenericObj):
       self.poa.deactivate_object(oid)
 
   def Destroy(self):
-    print "WARNING SALOME::GenericObj::Destroy() function is obsolete! Use UnRegister() instead."
+    print("WARNING SALOME::GenericObj::Destroy() function is obsolete! Use UnRegister() instead.")
     self.UnRegister()
 
 class PyNode_i (Engines__POA.PyNode,Generic):
@@ -62,27 +62,27 @@ class PyNode_i (Engines__POA.PyNode,Generic):
     ccode=compile(code,nodeName,'exec')
     self.context={}
     self.context["my_container"] = self.my_container
-    exec ccode in self.context
+    exec(ccode, self.context)
 
   def defineNewCustomVar(self,varName,valueOfVar):
-    self.context[varName] = cPickle.loads(valueOfVar)
+    self.context[varName] = pickle.loads(valueOfVar)
     pass
 
   def executeAnotherPieceOfCode(self,code):
     """Called for initialization of container lodging self."""
     try:
       ccode=compile(code,self.nodeName,'exec')
-      exec ccode in self.context
+      exec(ccode, self.context)
     except:
       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
 
   def execute(self,funcName,argsin):
     """Execute the function funcName found in local context with pickled args (argsin)"""
     try:
-      argsin,kws=cPickle.loads(argsin)
+      argsin,kws=pickle.loads(argsin)
       func=self.context[funcName]
       argsout=func(*argsin,**kws)
-      argsout=cPickle.dumps(argsout,-1)
+      argsout=pickle.dumps(argsout,-1)
       return argsout
     except:
       exc_typ,exc_val,exc_fr=sys.exc_info()
@@ -103,14 +103,14 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
     self.context["my_container"] = self.my_container
 
   def defineNewCustomVar(self,varName,valueOfVar):
-    self.context[varName] = cPickle.loads(valueOfVar)
+    self.context[varName] = pickle.loads(valueOfVar)
     pass
 
   def executeAnotherPieceOfCode(self,code):
     """Called for initialization of container lodging self."""
     try:
       ccode=compile(code,self.nodeName,'exec')
-      exec ccode in self.context
+      exec(ccode, self.context)
     except:
       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
 
@@ -124,15 +124,15 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
   def execute(self,outargsname,argsin):
     """Execute the script stored in attribute ccode with pickled args (argsin)"""
     try:
-      argsname,kws=cPickle.loads(argsin)
+      argsname,kws=pickle.loads(argsin)
       self.context.update(kws)
-      exec self.ccode in self.context
+      exec(self.ccode, self.context)
       argsout=[]
       for arg in outargsname:
-        if not self.context.has_key(arg):
+        if arg not in self.context:
           raise KeyError("There is no variable %s in context" % arg)
         argsout.append(self.context[arg])
-      argsout=cPickle.dumps(tuple(argsout),-1)
+      argsout=pickle.dumps(tuple(argsout),-1)
       return argsout
     except:
       exc_typ,exc_val,exc_fr=sys.exc_info()
index 4a118c8e8552b5c12d81c7b5b1fd56d7f8027e7e..7f673029d5b2917a6e0c42d2928d19af893fc634 100644 (file)
@@ -66,8 +66,8 @@ struct omniORBpyAPI {
 
 %init
 %{
+#include <capsulethunk.h>
   // init section
-
 #ifdef WITH_NUMPY
   import_array()
 #endif
@@ -77,10 +77,10 @@ struct omniORBpyAPI {
   {
     PyErr_SetString(PyExc_ImportError,
         (char*)"Cannot import _omnipy");
-    return;
+    return NULL;
   }
   PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
-  api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
+  api = (omniORBpyAPI*)PyCapsule_New(pyapi,NULL,NULL);
   Py_DECREF(pyapi);
 
   PyObject* engines = PyImport_ImportModule("Engines");
@@ -142,9 +142,11 @@ const char* pytype_string(PyObject* py_obj) {
   if (PyDict_Check(    py_obj)) return "dict"        ;
   if (PyList_Check(    py_obj)) return "list"        ;
   if (PyTuple_Check(   py_obj)) return "tuple"       ;
-  if (PyFile_Check(    py_obj)) return "file"        ;
   if (PyModule_Check(  py_obj)) return "module"      ;
+#if PY_MAJOR_VERSION < 3
+  if (PyFile_Check(    py_obj)) return "file"        ;
   if (PyInstance_Check(py_obj)) return "instance"    ;
+#endif
 
   return "unknown type";
 }
index 7948abe7f5dc99d7187f2d15e9e0884f104e0d28..9100c5694470ee49514e4c794b4a8e60d2b0f6bb 100755 (executable)
@@ -30,7 +30,7 @@ class SalomeDoc:
     def __init__(self, aDoc):
         self.doc = aDoc
     def __repr__(self):
-        print self.doc
+        print(self.doc)
         return "---"
     def salome(self):
         doc_salome = '''
@@ -80,7 +80,7 @@ methods:
   salome.DumpStudy(study) : Dump a study, given the ior
 ---
 '''
-        print doc_salome
+        print(doc_salome)
         
     def geompy(self):
         doc_geompy = '''
@@ -99,7 +99,7 @@ methods:
   --- all methods of GEOM_Gen.idl that returns a shape are encapsulated,
       with the same interface : shapes are named with their ior
 '''
-        print doc_geompy
+        print(doc_geompy)
         
     def supervision(self):
         doc_supervision = '''
@@ -128,7 +128,7 @@ A new python example avoids references to LifeCycleCORBA
                                    and GraphExample.xml
 ---
 '''
-        print doc_supervision
+        print(doc_supervision)
         
     
 
index f10973927e59a639e7d321877b66782a5d9c563d..79cec890e1de3a81d4b841c83304e891ce7b9877 100755 (executable)
@@ -50,7 +50,7 @@ def DumpComponent(Study, SO, offset):
             while ofs <= offset:
                 a = a + "--"
                 ofs = ofs +1
-            print a + ">" + CSO.GetID() + " " + t_name[1]
+            print(a + ">" + CSO.GetID() + " " + t_name[1])
         t_RefSO = CSO.ReferencedObject()
         if t_RefSO[0] == 1:
             RefSO = t_RefSO[1]
@@ -59,7 +59,7 @@ def DumpComponent(Study, SO, offset):
             while ofs <= offset:
                 a = a + "  "
                 ofs = ofs +1
-            print a + ">" + RefSO.GetID()
+            print(a + ">" + RefSO.GetID())
         DumpComponent(Study, CSO, offset+2)
 
     #--------------------------------------------------------------------------
@@ -70,7 +70,7 @@ def DumpStudy(Study):
         SC = itcomp.Value()
         itcomp.Next()
         name = SC.ComponentDataType()
-        print "-> ComponentDataType is " + name
+        print("-> ComponentDataType is " + name)
         DumpComponent(Study, SC, 1)
         
 
@@ -90,10 +90,10 @@ naming_service = SALOME_NamingServicePy_i(orb)
 
 # get active study name and id
 myStudyName = sg.getActiveStudyName()
-print myStudyName
+print(myStudyName)
 
 myStudyId = sg.getActiveStudyId()
-print myStudyId
+print(myStudyId)
 
 # get Study Manager reference
 obj = naming_service.Resolve('myStudyManager')
index 84f40c655522f7f09a873504c14e9752910dd7ed..16104045ad9abe095f5f63164ae67dcfb5078697 100755 (executable)
@@ -110,13 +110,13 @@ MATCH_ENDING_PATTERN="site-packages" + os.path.sep + "salome"
 
 def extend_path(pname):
     for dir in sys.path:
-        if not isinstance(dir, basestring) or not os.path.isdir(dir) or not dir.endswith(MATCH_ENDING_PATTERN):
+        if not isinstance(dir, str) or not os.path.isdir(dir) or not dir.endswith(MATCH_ENDING_PATTERN):
             continue
         subdir = os.path.join(dir, pname)
         # XXX This may still add duplicate entries to path on
         # case-insensitive filesystems
         if os.path.isdir(subdir) and subdir not in __path__:
-            if verbose(): print "INFO - The directory %s is appended to sys.path" % subdir
+            if verbose(): print("INFO - The directory %s is appended to sys.path" % subdir)
             __path__.append(subdir)
 
 extend_path(ROOT_PYTHONPACKAGE_NAME)
@@ -224,19 +224,19 @@ def salome_init(theStudyId=0,embedded=0):
             myStudyManager, myStudyId, myStudy, myStudyName = salome_study_init(theStudyId)
             pass
         pass
-    except RuntimeError, inst:
+    except RuntimeError as inst:
         # wait a little to avoid trace mix
         import time
         time.sleep(0.2)
         x = inst
-        print "salome.salome_init():", x
-        print """
+        print("salome.salome_init():", x)
+        print("""
         ============================================
         May be there is no running SALOME session
         salome.salome_init() is intented to be used
         within an already running session
         ============================================
-        """
+        """)
         raise
     
 def salome_close():
index 7a7ae9e819a1f075f0f1d8daa0dc3ea09946de65..d7645f7386d5f4f8e160f58fe3ee4f0ae288e620 100755 (executable)
@@ -65,12 +65,12 @@ def generateName(prefix = None):
     #WITHOUTIHMgetAllSelected = SalomeGUIgetAllSelected
    
     #WITHOUTIHMdef getDesktop(self) :
-#      return SalomePyQt.getDesktop()
-       #WITHOUTIHMreturn None
+#       return SalomePyQt.getDesktop()
+        #WITHOUTIHMreturn None
 
     #WITHOUTIHMdef getSelection(self) :
-#      return SalomePyQt.getSelection()
-       #WITHOUTIHMreturn None
+#       return SalomePyQt.getSelection()
+        #WITHOUTIHMreturn None
 
     #--------------------------------------------------------------------------
 
@@ -181,25 +181,25 @@ def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
     aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
 
     if not myStudyManager.CanCopy(theSO):
-        raise RuntimeError, "<CanCopy> for "+theInfo+" returns false"
+        raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
     
     if not myStudyManager.Copy(theSO):
-        raise RuntimeError, "<Copy> for "+theInfo+" returns false"
+        raise RuntimeError("<Copy> for "+theInfo+" returns false")
 
     
     if not myStudyManager.CanPaste(theSO):
-        raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
+        raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
 
     # check: before paste study is not changed check
     if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
-        raise RuntimeError, "Study is changed before Paste calling for "+theInfo
+        raise RuntimeError("Study is changed before Paste calling for "+theInfo)
     
     aSObj = theSO
     if theComponentPaste:
         aSObj = theSO.GetFatherComponent()
         theInfo = theInfo + "(paste for component)"
     if myStudyManager.Paste(aSObj) == None:
-        raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
+        raise RuntimeError("<Paste> for "+theInfo+" returns None object")
     aNewTree = GetTree(aRoot)
     aLen = len(aTree)
     for a in range(0,aLen):
@@ -209,7 +209,7 @@ def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
     if aLen < len(aNewTree):
         return myStudy.FindObjectID(aNewTree[aLen])
     
-    raise RuntimeError, "After Copy calling the tree is not changed"
+    raise RuntimeError("After Copy calling the tree is not changed")
     
     #--------------------------------------------------------------------------
 def FindFileInDataDir(filename):
@@ -246,7 +246,7 @@ while 1:
     pass
     
 if orb is None:
-    print "Warning: ORB has not been initialized !!!"
+    print("Warning: ORB has not been initialized !!!")
 
 # create an LifeCycleCORBA instance
 lcc = LifeCycleCORBA(orb)
@@ -264,7 +264,7 @@ while 1:
     pass
     
 if lcc is None:
-    print "Warning: LifeCycleCORBA object has not been initialized !!!"
+    print("Warning: LifeCycleCORBA object has not been initialized !!!")
     
 #create a naming service instance
 naming_service = SALOME_NamingServicePy_i(orb)
@@ -287,7 +287,7 @@ while 1:
 myStudyManager = obj._narrow(SALOMEDS.StudyManager)
 
 if myStudyManager is None:
-    print "Warning: SALOMEDS.StudyManager has not been created !!!"
+    print("Warning: SALOMEDS.StudyManager has not been created !!!")
 
 # create new study
 aListOfOpenStudies = myStudyManager.GetOpenStudies();
index f0b8c06a1ffb8e406d83767442323dc9d6996ab4..d3ce1c3d8569cda41547f16ff0b817c914b73da9 100755 (executable)
@@ -84,10 +84,10 @@ class IParameters:
         self._ap = attributeParameter
         if ( clr ): self.clear()
         pass
-       
+
     def clear(self):
         """Clear parameters"""
-       self._ap.Clear()
+        self._ap.Clear()
 
     def append(self, listName, value):
         """Appends a value to the named list"""
index 1dfd4f75093ec07f8ad4422873e8fe1bb006ce1d..65dda6ce6aadfa452c18456d5940c5562b0cc858 100644 (file)
@@ -80,18 +80,18 @@ class Callable:
 #
 
 def TEST_serialization():
-    from testdata import TestData
+    from .testdata import TestData
     ref_name = "my study case"
     studyData = TestData()
     studyData.setName(ref_name)
 
-    print "serialize data ..."
+    print("serialize data ...")
     serialString = serialize(studyData)
-    print "unserialize data ..."
+    print("unserialize data ...")
     unserialData = unserialize(serialString)
 
     res_name = unserialData.getName()
-    print res_name
+    print(res_name)
     if ( ref_name != res_name ):
         return False
 
@@ -101,5 +101,5 @@ def TEST_serialization():
     return True
 
 if __name__ == "__main__":
-    import unittester
+    from . import unittester
     unittester.run("salome/kernel/__init__","TEST_serialization")
index 9251b2a72f3c295d2a69e8e942369393591b7780..eec05050da70ee9988a9558489ecb65ea6c1323d 100644 (file)
@@ -26,7 +26,7 @@
 __author__="gboulant"
 __date__ ="$15 avr. 2010 19:44:17$"
 
-from uiexception import DevelException
+from .uiexception import DevelException
 
 # Most usable class types
 TypeString= "".__class__
@@ -105,7 +105,7 @@ class DataModeler:
         # Default initialization (if any)
         if defaultmap is not None:
             self._defaultmap.update(defaultmap)
-            for name in self._defaultmap.keys():
+            for name in list(self._defaultmap.keys()):
                 self.__setattr__(name,self._defaultmap[name])
 
     ## %A None argument means that no entry is created in the associated maps.
@@ -133,9 +133,9 @@ class DataModeler:
 
         #__GBO_DEBUG_
         if name == "_typemap":
-            print "WARNING WARNING WARNING : changing value of _typemap by ",val
+            print("WARNING WARNING WARNING : changing value of _typemap by ",val)
 
-        if name not in self._typemap.keys():
+        if name not in list(self._typemap.keys()):
             raise DevelException("The class "+str(self.__class__)+" has no attribute "+str(name))
 
         if val is None:
@@ -158,11 +158,11 @@ class DataModeler:
         if name in UNCHECKED_ATTRIBUTES:
             return self.__dict__[name]
 
-        if name not in self._typemap.keys():
+        if name not in list(self._typemap.keys()):
             raise DevelException("The class "+str(self.__class__)+" has no attribute "+str(name))
         # The attribute coulb be requested while it has not been created yet (for
         # example if we did't call the setter before).
-        if not self.__dict__.has_key(name):
+        if name not in self.__dict__:
             return None
         
         return self.__dict__[name]
@@ -177,7 +177,7 @@ class DataModeler:
     def __isNotValidRange(self, name, val):
         isNotValid = (
             ( self._rangemap is not None) and
-            ( self._rangemap.has_key(name) ) and
+            ( name in self._rangemap ) and
             ( self._rangemap[name] is not None ) and
             ( val not in self._rangemap[name] ) )
 
@@ -186,13 +186,13 @@ class DataModeler:
     def __isVoidAllowed(self,name):
         isVoidAllowed = (
             ( self._voidmap is not None) and
-            ( self._voidmap.has_key(name) ) and
+            ( name in self._voidmap ) and
             ( self._voidmap[name] is True ) )
             
         return isVoidAllowed
 
     def log(self):
-        print "DATAMODELER ["+str(self.__class__)+"]: self._typemap.keys() = "+str(self._typemap.keys())
+        print("DATAMODELER ["+str(self.__class__)+"]: self._typemap.keys() = "+str(list(self._typemap.keys())))
 
 
 
@@ -219,7 +219,7 @@ def TEST_usecase():
     data.anydata = "any value"
     data.anydata = True
 
-    print data.integerdata
+    print(data.integerdata)
     return True
 
 def TEST_addAttribute():
@@ -242,15 +242,15 @@ def TEST_addAttribute():
             return False
         data.myAttr = 5.3
         #data.myAttr = 5
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         return False
 
     try:
         data.myAttr = "bad type value"
         return False
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         return True
 
 def TEST_badAttributeName():
@@ -264,8 +264,8 @@ def TEST_badAttributeName():
     try:
         data.myatt = 3
         return False
-    except Exception, e:
-        print "OK : "+str(e)
+    except Exception as e:
+        print("OK : "+str(e))
         return True
 
 def TEST_badAttributeType():
@@ -278,8 +278,8 @@ def TEST_badAttributeType():
     try:
         data.stringdata = 2
         return False
-    except Exception, e:
-        print "OK : "+str(e)
+    except Exception as e:
+        print("OK : "+str(e))
         return True
 
 def TEST_badAttributeRange():
@@ -296,16 +296,16 @@ def TEST_badAttributeRange():
     try:
         data.integerdata = ref_integervalue
         data.stringdata = "anything (no restriction has been defined)"
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         return False
 
     # this should raise an exception
     try:
         data.integerdata = 9999 # a value not in the range
         return False
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         return True
 
 def TEST_voidAttributeAllowed():
@@ -320,17 +320,17 @@ def TEST_voidAttributeAllowed():
     try:
         # this should not raise an exception
         data.stringdata = None
-        print data.stringdata
-    except Exception, e:
-        print e
+        print(data.stringdata)
+    except Exception as e:
+        print(e)
         return False
     
     try:
         # this should raise an exception
         data.integerdata = None
         return False
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         return True
 
 def TEST_defaultValues():
@@ -343,14 +343,14 @@ def TEST_defaultValues():
     defaultmap["stringdata"] = ref_value
 
     data = DataModeler(typemap=typemap,defaultmap=defaultmap)
-    print data.stringdata
+    print(data.stringdata)
     if data.stringdata != ref_value:
         return False
     else:
         return True
 
 if __name__ == "__main__":
-    from unittester import run
+    from .unittester import run
     run("salome/kernel/datamodeler","TEST_usecase")
     run("salome/kernel/datamodeler","TEST_addAttribute")
     run("salome/kernel/datamodeler","TEST_badAttributeName")
index 263e6855c6a9c09fa4e2a9f482c88d6db7c26d66..613012600422bebae2ac43e795faf3405614cabd 100644 (file)
@@ -38,7 +38,7 @@ __date__ ="$21 mai 2010 18:00:23$"
 #  \ingroup diclookup
 def find_key(dic, val):
     """return the key of dictionary dic given the value"""
-    return [k for k, v in dic.iteritems() if v == val][0]
+    return [k for k, v in dic.items() if v == val][0]
 
 ## return the value of dictionary dic given the key
 #  \ingroup diclookup
@@ -55,14 +55,14 @@ class Lookup(dict):
     ## items can be a list of pair_lists or a dictionary
     def __init__(self, items=None):
         """items can be a list of pair_lists or a dictionary"""
-       if items is None:
-           items = []
+        if items is None:
+            items = []
         dict.__init__(self, items)
 
     ## find the key(s) as a list given a value
     def get_keys(self, value):
         """find the key(s) as a list given a value"""
-        return [item[0] for item in self.items() if item[1] == value]
+        return [item[0] for item in list(self.items()) if item[1] == value]
 
     ## find the key associated to the given a value. If several keys exist,
     #  only the first is given. To get the whole list, use get_keys instead.
@@ -100,9 +100,9 @@ def TEST_getTestDictionnary():
 
 def TEST_find_value():
     symbol_dic = TEST_getTestDictionnary()
-    print find_key(symbol_dic, 'boron')  # B
-    print find_value(symbol_dic, 'B')    # boron
-    print find_value(symbol_dic, 'H')    # hydrogen
+    print(find_key(symbol_dic, 'boron'))  # B
+    print(find_value(symbol_dic, 'B'))    # boron
+    print(find_value(symbol_dic, 'H'))    # hydrogen
     if find_key(symbol_dic, 'nitrogen') != 'N':
         return False
     return True
@@ -114,24 +114,24 @@ def TEST_lookup():
     symbol = 'Li'
     # use a dictionary as initialization argument
     look = Lookup(symbol_dic)
-    print look.get_key(name)      # [Li']
+    print(look.get_key(name))      # [Li']
     if look.get_key(name) != symbol:
-        print "get "+str(look.get_key(name))+" while "+str(symbol)+" was expected"
+        print("get "+str(look.get_key(name))+" while "+str(symbol)+" was expected")
         return False
-    print look.get_value(symbol)  # lithium
+    print(look.get_value(symbol))  # lithium
 
     # use a list of pairs instead of a dictionary as initialization argument
     # (will be converted to a dictionary by the class internally)
     age_list = [['Fred', 23], ['Larry', 28], ['Ene', 23]]
     look2 = Lookup(age_list)
-    print look2.get_keys(23)        # ['Ene', 'Fred']
+    print(look2.get_keys(23))        # ['Ene', 'Fred']
     if look2.get_keys(23)[0] != 'Ene' or look2.get_keys(23)[1] != 'Fred':
-        print "get "+str(look2.get_keys(23))+" while ['Ene', 'Fred'] was expected"
+        print("get "+str(look2.get_keys(23))+" while ['Ene', 'Fred'] was expected")
         return False
-    print look2.get_value('Fred')  # 23
+    print(look2.get_value('Fred'))  # 23
     return True
 
 if __name__ == '__main__':
-    import unittester
+    from . import unittester
     unittester.run("diclookup", "TEST_find_value")
     unittester.run("diclookup", "TEST_lookup")
index e6fdff96c7a88af34ecfa9e67ae1d7b236676a81..5111c916fa3c072de15788577349048650233f96 100644 (file)
@@ -61,7 +61,7 @@ class Enumerate(object):
         Return true if this enumerate contains the specified key string
         @key a key string to test
         """
-        return (key in self._dict_keynumbers.keys())
+        return (key in list(self._dict_keynumbers.keys()))
 
     ## Returns true if the specified integer value is defined as an identifier
     #  in this enumarate.
@@ -72,14 +72,14 @@ class Enumerate(object):
         in this enumarate.
         @value a value to test
         """
-        return (value in self._dict_keynumbers.values())
+        return (value in list(self._dict_keynumbers.values()))
 
     ## Returns the list of keys in this enumerate.
     def listkeys(self):
         """
         Returns the list of keys in this enumerate.
         """
-        list = self._dict_keynumbers.keys()
+        list = list(self._dict_keynumbers.keys())
         list.sort()
         return list
 
@@ -88,7 +88,7 @@ class Enumerate(object):
         """
         Returns the list of values specified to initiate this enumerate.
         """
-        list = self._dict_keynumbers.values()
+        list = list(self._dict_keynumbers.values())
         list.sort()
         return list
 
@@ -104,7 +104,7 @@ class Enumerate(object):
             return None
         # _MEM_ We assume here that the keys and associated values are in the
         # same order in their list.
-        return self._dict_keynumbers.keys()[self._dict_keynumbers.values().index(value)]
+        return list(self._dict_keynumbers.keys())[list(self._dict_keynumbers.values()).index(value)]
 
         # If not, weshould use a longer implementation such that:
         #for key in self._dict_keynumbers.keys():
@@ -122,7 +122,7 @@ def TEST_simple():
         'SEP',
         'OTHER'
     ])
-    print TYPES_LIST.listvalues()
+    print(TYPES_LIST.listvalues())
     return True
 
 def TEST_createFromList():
@@ -133,8 +133,8 @@ def TEST_createFromList():
         'MED',
         'SMESH'])
 
-    print codes.KERNEL
-    print codes.GEOM
+    print(codes.KERNEL)
+    print(codes.GEOM)
     if (codes.KERNEL == 0 and codes.GEOM == 2):
         return True
     else:
@@ -145,8 +145,8 @@ def TEST_createFromString():
 
     codes = Enumerate(aList.split())
 
-    print codes.KERNEL
-    print codes.GEOM
+    print(codes.KERNEL)
+    print(codes.GEOM)
     if (codes.KERNEL == 0 and codes.GEOM == 2):
         return True
     else:
@@ -160,7 +160,7 @@ def TEST_contains():
         'MED',
         'SMESH'])
 
-    print "VISU in enumerate?", codes.contains("VISU")
+    print("VISU in enumerate?", codes.contains("VISU"))
     if (not codes.contains("VISU")):
         return True
     else:
@@ -187,8 +187,8 @@ def TEST_offset():
         'MED',
         'SMESH'], offset=20)
 
-    print codes.KERNEL
-    print codes.GEOM
+    print(codes.KERNEL)
+    print(codes.GEOM)
     if (codes.KERNEL == 20 and codes.GEOM == 22):
         return True
     else:
@@ -202,7 +202,7 @@ def TEST_listvalues():
         'MED',
         'SMESH'], offset=20)
 
-    print codes.listvalues()
+    print(codes.listvalues())
     if codes.listvalues() != [20, 21, 22, 23, 24]:
         return False
     return True
@@ -224,7 +224,7 @@ def TEST_keyOf():
     return True
 
 if __name__ == "__main__":
-    import unittester
+    from . import unittester
     unittester.run("enumerate", "TEST_simple")
     unittester.run("enumerate", "TEST_createFromList")
     unittester.run("enumerate", "TEST_createFromString")
index 0ac0490fcbb8e4d04f90aa7e9afb9b2d4629577f..4a8cfa5cd5c84db7fca6a07b4a009641e1cff3cf 100644 (file)
@@ -53,7 +53,7 @@ class Variable:
     def __init__(self, name, dimension = None, minValue = None, maxValue = None,
                  initialValue = None):
         if dimension is None:
-         dimension = []
+            dimension = []
         self.name = name
         
         # Reserved for future use
@@ -105,9 +105,9 @@ class ExchangeVariables:
     def __init__(self, inputVarList = None, outputVarList = None,
                  refEntry = None):
         if inputVarList is None:
-         inputVarList = []
-       if outputVarList is None:
-         outputVarList = []
+            inputVarList = []
+        if outputVarList is None:
+            outputVarList = []
         self.inputVarList = inputVarList
         self.outputVarList = outputVarList
         self.refEntry = refEntry
index fa011080b92408734417d21720eaae7429f119a4..76e79d0ae246940f6e05905f124ce886091adc61 100644 (file)
@@ -30,16 +30,16 @@ def printfile(filename):
     lines = stream.readlines()
     stream.close()
     for line in lines:
-       if not termcolor.canDisplayColor(sys.stdout):
-           msg = line.split('\n')[0]
-       else:
+        if not termcolor.canDisplayColor(sys.stdout):
+            msg = line.split('\n')[0]
+        else:
             msg = termcolor.makeColoredMessage(line.split('\n')[0], termcolor.BLUE)
-        print msg
+        print(msg)
 
 import os
 import unittest
 from unittest import TestCase
-from uiexception import DevelException
+from .uiexception import DevelException
 
 ## This class is a simple wrapper of the pyunit framework.
 #  \ingroup pyunittester
@@ -97,8 +97,8 @@ def execAndConvertExceptionToBoolean(function):
         if result is None:
             return True
         return result
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         return False
 
 # Simple helper function for most cases where there is only one
@@ -121,17 +121,17 @@ def run(testCaseClass):
 class MyTestCase(unittest.TestCase):
     def test_myTestOk_01(self):
         r=True
-        print "myTestOk_01: should be OK"
+        print("myTestOk_01: should be OK")
         self.assertTrue(r)
 
     def test_myTestOk_02(self):
         r=True
-        print "myTestOk_02: should be OK"
+        print("myTestOk_02: should be OK")
         self.assertTrue(r)
 
     def test_myTestNotOk(self):
         r=False
-        print "myTestNotOk: should be NOT OK"
+        print("myTestNotOk: should be NOT OK")
         self.assertTrue(r)
 
 def functionRaisingAnException():
@@ -144,32 +144,32 @@ def functionReturningTrue():
     return True
 
 def functionReturningNothing():
-    print "functionReturningNothing"
+    print("functionReturningNothing")
 
 class MyTestCase2(unittest.TestCase):
     def test_myTest_01(self):
         r=execAndConvertExceptionToBoolean(functionRaisingAnException)
-        print "test 01: this test should be NOT OK"
+        print("test 01: this test should be NOT OK")
         self.assertTrue(r)
 
     def test_myTest_02(self):
         r=execAndConvertExceptionToBoolean(functionReturningFalse)
-        print "test 02: this test should be NOT OK"
+        print("test 02: this test should be NOT OK")
         self.assertTrue(r)
 
     def test_myTest_03(self):
         r=execAndConvertExceptionToBoolean(functionReturningTrue)
-        print "test 03: this test should be OK"
+        print("test 03: this test should be OK")
         self.assertTrue(r)
 
     def test_myTest_04(self):
         r=execAndConvertExceptionToBoolean(functionReturningNothing)
-        print "test 04: this test should be OK"
+        print("test 04: this test should be OK")
         self.assertTrue(r)
 
     def test_myTest_05(self):
         r=True
-        print "test 05: this test should be OK"
+        print("test 05: this test should be OK")
         self.assertTrue(r)
 
 
index a2d4feaa684eefe2f41da1e238c1bc8ab74de9eb..5e6c8db0fbc273d15301f30f6f8db71b0d8bbc73 100644 (file)
 # SALOME development).
 
 import salome
-from deprecation import is_called_by_sphinx
+from .deprecation import is_called_by_sphinx
 if not is_called_by_sphinx() and salome.lcc is None:
     try:
         salome.salome_init()
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
 
 # Note that the salome module provides you with standard SALOME
 # objects: CORBA broker (orb): salome.orb lyfe cycle (lcc) :
@@ -96,12 +96,12 @@ def getComponent(componentName = "SalomeTestComponent",
     """
     Get a SALOME CORBA component from its name
     """
-    print "INF: getting component %s from CORBA module %s ..."%(componentName,corbaModule)
+    print("INF: getting component %s from CORBA module %s ..."%(componentName,corbaModule))
     __import__(corbaModule)
     component=salome.lcc.FindOrLoadComponent(containerType,componentName)
     if component is None:
-        print "ERR: the SALOME component "+componentName+" can't be reached"
-    print "INF: component %s obtained from CORBA module %s"%(componentName,corbaModule)
+        print("ERR: the SALOME component "+componentName+" can't be reached")
+    print("INF: component %s obtained from CORBA module %s"%(componentName,corbaModule))
     return component
 
 # Note that an alternative (and maybe better) method to get a component
@@ -120,7 +120,7 @@ def getComponentList():
     obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
     catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
     if not catalog:
-        raise RuntimeError, "Can't accesss module catalog"
+        raise RuntimeError("Can't accesss module catalog")
     return catalog.GetComponentList()
 
 ## Get a study manager to create and manage %SALOME studies
@@ -259,14 +259,14 @@ def TEST_objectsManipulation():
 
 
     myObject = IDToObject(myEntry)
-    print myObject
+    print(myObject)
     if myObject is None:
         return False
 
     return True
 
 if __name__ == "__main__":
-    import unittester
+    from . import unittester
     unittester.run("services","TEST_getComponent")
     unittester.run("services","TEST_getComponentList")
     unittester.run("services","TEST_objectsManipulation")
index 463b70fb859d7160472f005c8a14e0e3ee1ca538..2b0d41e662e906d2d0bfab55ff62e5de08a06904 100644 (file)
@@ -84,7 +84,7 @@ def getStudyEditor(studyId = None):
     """
     if studyId is None:
         studyId = getActiveStudyId()
-    if not _editors.has_key(studyId):
+    if studyId not in _editors:
         _editors[studyId] = StudyEditor(studyId)
     return _editors[studyId]
 
@@ -541,7 +541,7 @@ class StudyEditor:
     ## Return the name of the object sObject
     def getName(self, sObject):
         val = sObject.GetName()
-        return unicode(val, ENCODING_FOR_SALOME_STUDY)
+        return str(val, ENCODING_FOR_SALOME_STUDY)
 
     ## Set the name of the object sObject
     def setName(self, sObject, name):
@@ -550,7 +550,7 @@ class StudyEditor:
     ## Return the comment of the object sObject
     def getComment(self, sObject):
         val = sObject.GetComment()
-        return unicode(val, ENCODING_FOR_SALOME_STUDY)
+        return str(val, ENCODING_FOR_SALOME_STUDY)
 
     ## Set the comment of the object sObject
     def setComment(self, sObject, comment):
@@ -605,7 +605,7 @@ class StudyEditor:
         `sObject`, or an empty string if it is not set.
         """
         val = self.getAttributeValue(sObject, "AttributeFileType", "")
-        return unicode(val, ENCODING_FOR_SALOME_STUDY)
+        return str(val, ENCODING_FOR_SALOME_STUDY)
 
     ## Set the attribute "AttributeFileType" of the object sObject to the
     #  value value.
@@ -625,7 +625,7 @@ class StudyEditor:
         object `sObject`, or an empty string if it is not set.
         """
         val = self.getAttributeValue(sObject, "AttributeExternalFileDef", "")
-        return unicode(val, ENCODING_FOR_SALOME_STUDY)
+        return str(val, ENCODING_FOR_SALOME_STUDY)
 
     ## Set the attribute "AttributeExternalFileDef" of the object sObject
     #  to the value value.
@@ -648,7 +648,7 @@ class StudyEditor:
         found, attr = self.builder.FindAttribute(sObject, "AttributePixMap")
         if found and attr.HasPixMap():
             value = attr.GetPixMap()
-        return unicode(value, ENCODING_FOR_SALOME_STUDY)
+        return str(value, ENCODING_FOR_SALOME_STUDY)
 
     ## Set the attribute "AttributePixMap" of the object sObject to the
     #  value value.
index f3c94600df0d86459942b9a2b51d59e858d45e8b..31e079fc4aee23a67bc66549e8b867e4a386fd3c 100644 (file)
@@ -55,10 +55,12 @@ def walktree(rootpath, callback, **kwargs):
     calling the callback function for each regular file
     '''
     for f in os.listdir(rootpath):
+        print(f)
         pathname = os.path.join(rootpath, f)
+        print(pathname)
         try:
             mode = os.stat(pathname)[ST_MODE]
-        except OSError, e:
+        except OSError as e:
             # It probably means that the file is a broken inode
             mode = -1
         if S_ISDIR(mode):
@@ -69,7 +71,7 @@ def walktree(rootpath, callback, **kwargs):
             callback(pathname, **kwargs)
         else:
             # Unknown file type, print a message
-            print 'Skipping %s' % pathname
+            print('Skipping %s' % pathname)
 
 
 #
@@ -84,26 +86,26 @@ except KeyError:
     TESTDOCDIR="/tmp"
     
 def TEST_findFiles():
-    print "########## find 1"
+    print("########## find 1")
     rootpath=TESTDOCDIR
     listfiles=findFiles(rootpath)
     for filename in listfiles:
-        print filename
+        print(filename)
 
-    print "########## find 2"
+    print("########## find 2")
     excludes=[os.path.join(TESTDOCDIR,"doc")]
     listfiles=findFiles(rootpath,excludes)
     for filename in listfiles:
-        print filename
+        print(filename)
 
     return True
 
 # This is the test callback function
 def visitfile_withargs(file, rootid):
-    print 'visiting file %s (rootid=%s)'%(file,str(rootid))
+    print('visiting file %s (rootid=%s)'%(file,str(rootid)))
 
 def visitfile_withoutargs(file):
-    print 'visiting file %s'%(file)
+    print('visiting file %s'%(file))
 
 def TEST_walktree():
     #walktree(TESTDOCDIR, visitfile_withargs, rootid=2)
@@ -111,6 +113,6 @@ def TEST_walktree():
     return True
 
 if __name__ == "__main__":
-    import unittester
+    from . import unittester
     unittester.run("syshelper", "TEST_findFiles")
     unittester.run("syshelper", "TEST_walktree")
index b7d99c778037b890d6379bdc407ab1fc82e94b8e..33476f74759dee09220726fa210bada02f72c666 100644 (file)
@@ -225,13 +225,13 @@ def TEST_termcolor():
     """Test function for termcolor module."""
     import sys
     if not canDisplayColor(sys.stdout):
-        print "Standard output does not support colors."
+        print("Standard output does not support colors.")
         return
-    print makeColoredMessage("This message must appear in blue.", BLUE)
-    print makeColoredMessage("This message must appear in red on green " +
-                             "background.", RED + GREEN_BG)
-    print makeColoredMessage("This message must appear in magenta and " +
-                             "crossed-out.", PURPLE + ['09'])
+    print(makeColoredMessage("This message must appear in blue.", BLUE))
+    print(makeColoredMessage("This message must appear in red on green " +
+                             "background.", RED + GREEN_BG))
+    print(makeColoredMessage("This message must appear in magenta and " +
+                             "crossed-out.", PURPLE + ['09']))
 
 
 # Main function only used to test the module
index 21cd9ee6af956d11ff73fc6b430caa90cb03ae3e..ffbb0dcc934b6d1b02c907c5aafa53a137695534 100644 (file)
@@ -24,8 +24,8 @@
 __author__="gboulant"
 __date__ ="$17 avr. 2010 19:44:36$"
 
-from enumerate import Enumerate
-from datamodeler import DataModeler, TypeString, TypeInteger
+from .enumerate import Enumerate
+from .datamodeler import DataModeler, TypeString, TypeInteger
 from salome.kernel import Callable
 
 class TestData(DataModeler):
@@ -79,7 +79,7 @@ class TestData(DataModeler):
 # Basic use cases and unit tests
 # ==============================================================================
 #
-from uiexception import UiException
+from .uiexception import UiException
 
 def TEST_getName():
     testdata = TestData()
@@ -96,8 +96,8 @@ def TEST_useBadKey():
         testdata.unknown = "unknown"
         # This should not arrive here
         return False
-    except UiException, err:
-        print err
+    except UiException as err:
+        print(err)
         return True
 
 def TEST_useBadType():
@@ -106,8 +106,8 @@ def TEST_useBadType():
         testdata.TYPE = "unknown"
         # This should not arrive here
         return False
-    except UiException, err:
-        print err
+    except UiException as err:
+        print(err)
         return True
 
 def TEST_useBadRange():
@@ -117,17 +117,17 @@ def TEST_useBadRange():
         testdata.TYPE = TestData.TYPES_LIST.SEP
         testdata.setType(TestData.TYPES_LIST.SEP)
         # This should arrive here
-    except UiException, err:
+    except UiException as err:
         # And not here
-        print err
+        print(err)
         return False
 
     try:
         testdata.TYPE = 9999 # a type that does not exist in the range
         # This should not arrive here
         return False
-    except UiException, err:
-        print err
+    except UiException as err:
+        print(err)
         return True
 
 def TEST_serialize():
@@ -136,7 +136,7 @@ def TEST_serialize():
     ref_testdata.setName("The firts name")
     res_testdata = salome.kernel.unserialize(salome.kernel.serialize(ref_testdata))
 
-    print res_testdata.getName()
+    print(res_testdata.getName())
 
     if res_testdata.getName() != ref_testdata.getName():
         return False
@@ -144,14 +144,14 @@ def TEST_serialize():
     # Is the unserialized data still functional?
     try:
         res_testdata.setName("An other name")
-        print res_testdata.getName()
+        print(res_testdata.getName())
     except:
-        print e
+        print(e)
         return False
     return True
 
 if __name__ == "__main__":
-    from unittester import run
+    from .unittester import run
     run("salome/kernel/testdata","TEST_getName")
     run("salome/kernel/testdata","TEST_useBadKey")
     run("salome/kernel/testdata","TEST_useBadType")
index c71a9a54396ee5b6625acc3e67474ee13e6b0ed0..b6d6b06893aa6b493df798b9fd8510fa5cd918a4 100644 (file)
@@ -88,12 +88,12 @@ class Runner(threading.Thread):
         Ex�cution de la fonction. Impl�mentation de la m�thode run
         d�clench�e par l'appel ï¿½ Thread.start().
         """
-        print "##################### threadhelper.run"
+        print("##################### threadhelper.run")
         if self._function is None: return
         try:
             self._return = self._function(*self._argv)
-        except Exception, e:
-            print e
+        except Exception as e:
+            print(e)
             self._exception = e
         self._stopevent.set()
         self.notifyObserver()
@@ -107,15 +107,15 @@ class Runner(threading.Thread):
             return
         try:
             self._observer.processNotification()
-        except AttributeError, att:
+        except AttributeError as att:
             if str(att) == "processNotification":
-                print "L'observateur n'impl�mente pas la m�thode processNotification()"
+                print("L'observateur n'impl�mente pas la m�thode processNotification()")
             else:
-                print "La fonction processNotification() a lev� une exception:"
-                print att
-        except Exception, e:
-            print "La fonction processNotification() a lev� une exception:"
-            print e
+                print("La fonction processNotification() a lev� une exception:")
+                print(att)
+        except Exception as e:
+            print("La fonction processNotification() a lev� une exception:")
+            print(e)
 
     def callback(self):
         if self._callbackFunction is None: return
@@ -232,14 +232,14 @@ class PeriodicTimer( threading.Thread ):
 import os
 testfilename="/tmp/threadhelperTestFile"
 def testIfContinue():
-    print "On examine la pr�sence du fichier ", testfilename
+    print("On examine la pr�sence du fichier ", testfilename)
     if os.path.exists(testfilename):
         return STOP
     else:
         return CONTINUE
 
 def endedAction():
-    print "FINI"
+    print("FINI")
 
 def TEST_PeriodicTimer():
     periodicTimer=PeriodicTimer(1,0,testIfContinue, endedAction)
@@ -251,43 +251,43 @@ def function_ok(nbsteps=5):
     """
     Fonction qui se termine correctement
     """
-    print "D�but"
+    print("D�but")
     cnt=0
     while ( cnt < nbsteps ):
-        print "Etape ", cnt
+        print("Etape ", cnt)
         time.sleep(0.6)
         cnt+=1
 
-    print "Fin"
+    print("Fin")
 
 def function_with_exception():
     """
     Fonction qui aboutie ï¿½ une lev�e d'exception
     """
-    print "D�but"
+    print("D�but")
     cnt=0
     while ( cnt < 5 ):
-        print "Etape ", cnt
+        print("Etape ", cnt)
         time.sleep(1)
         cnt+=1
     
     raise Exception("erreur d'ex�cution de la fonction")
-    print "Fin"
+    print("Fin")
 
 def infinite_function():
     """
     fonction de dur�e infinie (tant qu'il y a du courant ï¿½l�ctrique) pour
     le test du timeout.
     """
-    print "D�but"
+    print("D�but")
     cnt=0
     while ( 1 ):
-        print "Etape ", cnt
+        print("Etape ", cnt)
         time.sleep(1)
         cnt+=1
     
     raise Exception("erreur")
-    print "Fin"
+    print("Fin")
 
 
 def runWithRunner(functionToRun):
@@ -295,21 +295,21 @@ def runWithRunner(functionToRun):
     Ex�cute la fonction avec le runner. On illustre ici la modalit�
     d'utilisation du Runner.
     """
-    print "###########"
+    print("###########")
     runner = Runner(functionToRun)
     runner.start()
 
     while ( not runner.isEnded() ):
-        print "La fonction est en cours"
+        print("La fonction est en cours")
         time.sleep(0.2)
     e = runner.getException()
     if e is not None:
-        print "La fonction s'est termin�e en erreur"
-        print e
+        print("La fonction s'est termin�e en erreur")
+        print(e)
         # On peut en fait la relancer
         # raise e
     else:
-        print "La fonction s'est termin�e correctement"
+        print("La fonction s'est termin�e correctement")
 
 
 def runWithTimeout(functionToRun, timeout=10):
@@ -317,26 +317,26 @@ def runWithTimeout(functionToRun, timeout=10):
     Ex�cute la fonction avec le runner. On illustre ici la modalit�
     d'utilisation du Runner.
     """
-    print "runWithTimeout : DEBUT"
+    print("runWithTimeout : DEBUT")
     runner = Runner(functionToRun)
     runner.start()
 
     # On se fixe un temps au del� duquel on consid�re que la fonction
     # est en erreur => on tue le thread (timeout)
     runner.wait(timeout)
-    print "Apr�s runner.timeout(timeout)"
+    print("Apr�s runner.timeout(timeout)")
     if not runner.isEnded():    
         runner.kill()
     e = runner.getException()
     if e is not None:
-        print "La fonction s'est termin�e en erreur"
-        print e
+        print("La fonction s'est termin�e en erreur")
+        print(e)
         # On peut en fait la relancer
         # raise e
     else:
-        print "La fonction s'est termin�e correctement"
+        print("La fonction s'est termin�e correctement")
 
-    print "runWithTimeout : FIN"
+    print("runWithTimeout : FIN")
     import sys
     sys.exit(0)
     
@@ -354,7 +354,7 @@ def TEST_Runner():
 
 
 def myCallbackFunction():
-    print "myCallbackFunction: the job is ended"
+    print("myCallbackFunction: the job is ended")
     
 
 def TEST_runWithCallback():
@@ -366,17 +366,17 @@ def TEST_runWithCallback():
         return False
 
     runnerId = runner.getId()
-    print "A runner has been started with id="+str(runnerId)
+    print("A runner has been started with id="+str(runnerId))
     cpt = 0
     while ( not runner.isEnded() ):
-        print "Waiting notification from process "+str(runner.getId())+", step n°"+str(cpt)
+        print("Waiting notification from process "+str(runner.getId())+", step n°"+str(cpt))
         time.sleep(0.2)
         cpt+=1
 
     return True
 
 if __name__ == "__main__":
-    import unittester
+    from . import unittester
     #TEST_PeriodicTimer()
     #TEST_Runner()
     #TEST_Timeout()
index d1d2c8e2e38b6292e32e7e3b96d0b16a26124c33..bb1928e49945453f648ea72bd41e0a3c4d26f008 100644 (file)
@@ -26,7 +26,7 @@
 __author__="gboulant"
 __date__ ="$31 mars 2010 11:59:33$"
 
-from enumerate import Enumerate
+from .enumerate import Enumerate
 
 ## This exception should be used for functionnal error management, at least in the GUI
 #  part of the application, for example to set user oriented messages at point
@@ -101,21 +101,21 @@ def TEST_uimessage():
     try:
         somethingGoesWrong()
         return False
-    except UiException, err:
-        print 'ERROR: %s' % str(err)
+    except UiException as err:
+        print('ERROR: %s' % str(err))
         if ( str(err) == "Something goes wrong" ):
             return True
         else:
             return False
 
 def TEST_specificException():
-    print DevelException("err")
-    print AdminException("err")
-    print UserException("err")
+    print(DevelException("err"))
+    print(AdminException("err"))
+    print(UserException("err"))
     return True
 
 if __name__ == "__main__":
-    import unittester
+    from . import unittester
     unittester.run("uiexception","TEST_uimessage")
     unittester.run("uiexception","TEST_specificException")
     
index be7c3baac94b7286ef5a565d00939a8d3616c856..dc447b6f1b9d320fb81abf3098f3e5adf2b382a9 100644 (file)
@@ -45,12 +45,12 @@ def run(modulePath, functionName):
     module=sys.modules[moduleName]
     func = getattr(module,functionName)
     tabsize = 70-len(moduleName)-len(functionName)
-    print "[TEST] %s.%s %s test in progress" % (moduleName, functionName,"."*tabsize
+    print("[TEST] %s.%s %s test in progress" % (moduleName, functionName,"."*tabsize)
     ok = func()
     if ( ok ):
-        print "[TEST] %s.%s %s OK" % (moduleName, functionName,"."*tabsize)
+        print("[TEST] %s.%s %s OK" % (moduleName, functionName,"."*tabsize))
     else:
-        print "[TEST] %s.%s %s NOT OK" % (moduleName, functionName,"."*tabsize)
+        print("[TEST] %s.%s %s NOT OK" % (moduleName, functionName,"."*tabsize))
 
 ## This function is for debug only. It executes the specified function with the
 #  specified arguments in a try/except bloc so that to display the exception in
@@ -64,11 +64,11 @@ def tryfunction(function,*argv):
     the case where an exception is raised (usefull to debug server side of a CORBA
     process).
     """
-    print "[TEST] trying the function %s" % function
+    print("[TEST] trying the function %s" % function)
     try:
         return function(*argv)
-    except Exception, e:
-        print e
+    except Exception as e:
+        print(e)
         raise e
 
 
index 1e2c0e7c6b21e28b38a305ada5d9561c5460f27b..29dd1e4f8929274a5ea28719948a73e481732376 100644 (file)
@@ -51,10 +51,10 @@ def openModule(mname, fname=None):
         shared_imported[mname]=mod
         # Salome modification end
 
-    elif sys.modules.has_key(mname):
+    elif mname in sys.modules:
         mod = sys.modules[mname]
 
-        if _partialModules.has_key(mname):
+        if mname in _partialModules:
             pmod = _partialModules[mname]
             mod.__dict__.update(pmod.__dict__)
             del _partialModules[mname]
@@ -62,7 +62,7 @@ def openModule(mname, fname=None):
         shared_imported[mname]=mod
         # Salome modification end
 
-    elif _partialModules.has_key(mname):
+    elif mname in _partialModules:
         mod = _partialModules[mname]
 
     # Salome modification start
@@ -98,10 +98,10 @@ def newModule(mname):
     for name in mlist:
         current = current + name
 
-        if sys.modules.has_key(current):
+        if current in sys.modules:
             mod = sys.modules[current]
 
-        elif _partialModules.has_key(current):
+        elif current in _partialModules:
             mod = _partialModules[current]
 
         else:
@@ -120,7 +120,7 @@ def updateModule(mname):
     # Be sure to use the right module dictionnary
     import sys
     # Salome modification end
-    if _partialModules.has_key(mname):
+    if mname in _partialModules:
         pmod = _partialModules[mname]
         mod  = sys.modules[mname]
         mod.__dict__.update(pmod.__dict__)
index 9baeb7d5ddf90f67d7add9dcb194f933f23787f0..6afcdfa6bf833dab447dbd5a786c0c6a255b8fbe 100644 (file)
@@ -41,12 +41,10 @@ def getShapeTypeString(aSubId):
 
 def createAndDisplayGO( *args, **kwargs ):
     pass
-                       
     #--------------------------------------------------------------------------
 
 def UpdateViewer():
-    pass                                               
-                                                       
+    pass
     #--------------------------------------------------------------------------
 
 def setDisplayMode(objId, mode):
index 283c5685c79997a4dfb57e919db92bc1b9d63c7a..771a68a048fe55d8636f054e5e768f488543f843 100755 (executable)
@@ -44,8 +44,8 @@ def ImportComponentGUI(ComponentName):
         exec ( command )
         return gui
     else:
-        print "Warning: ImportComponentGUI(",ComponentName,") outside GUI !"
-        print "calls to GUI methods may crash..."
+        print("Warning: ImportComponentGUI(",ComponentName,") outside GUI !")
+        print("calls to GUI methods may crash...")
         return salome_ComponentGUI
 
     #--------------------------------------------------------------------------
@@ -79,82 +79,82 @@ class SalomeOutsideGUI(object):
     
     def updateObjBrowser(self, bid):
         """update the GUI object browser"""
-        print "SalomeOutsideGUI: no objectBrowser update outside GUI"
+        print("SalomeOutsideGUI: no objectBrowser update outside GUI")
         pass
     
     def getActiveStudyId(self):
         """Get the active study id"""
-        print "SalomeOutsideGUI.getActiveStudyId: avoid use outside GUI"
+        print("SalomeOutsideGUI.getActiveStudyId: avoid use outside GUI")
         return myStudyId
     
     def getActiveStudyName(self):
         """Get the active study name"""
-        print "SalomeOutsideGUI.getActiveStudyName: avoid use outside GUI"
+        print("SalomeOutsideGUI.getActiveStudyName: avoid use outside GUI")
         return myStudyName
     
     def SelectedCount(self):
         """Get the number of active selections"""
-        print "SalomeOutsideGUI: no selection mecanism available outside GUI"
+        print("SalomeOutsideGUI: no selection mecanism available outside GUI")
         return 0
     
     def getSelected(self, i):
         """Get the selection number i """
-        print "SalomeOutsideGUI: no selection mecanism available outside GUI"
+        print("SalomeOutsideGUI: no selection mecanism available outside GUI")
         return none
     
     def AddIObject(self, Entry):
         """Add an entry"""
-        print "SalomeOutsideGUI.AddIOObject: not available outside GUI"
+        print("SalomeOutsideGUI.AddIOObject: not available outside GUI")
         pass
     
     def RemoveIObject(self, Entry):
         """Remove an entry"""
-        print "SalomeOutsideGUI.REmoveIOObject: not available outside GUI"
+        print("SalomeOutsideGUI.REmoveIOObject: not available outside GUI")
         pass
     
     def ClearIObjects(self):
         """Clear entries"""
-        print "SalomeOutsideGUI.ClearIOObject: not available outside GUI"
+        print("SalomeOutsideGUI.ClearIOObject: not available outside GUI")
         pass
     
     def Display(self, Entry):
         """Display an entry"""
-        print "SalomeOutsideGUI.Display: not available outside GUI"
+        print("SalomeOutsideGUI.Display: not available outside GUI")
         pass
     
     def DisplayOnly(self, Entry):
         """Display only an entry"""
-        print "SalomeOutsideGUI.DisplayOnly: not available outside GUI"
+        print("SalomeOutsideGUI.DisplayOnly: not available outside GUI")
         pass
     
     def Erase(self, Entry):
         """Erase en entry"""
-        print "SalomeOutsideGUI.Erase: not available outside GUI"
+        print("SalomeOutsideGUI.Erase: not available outside GUI")
         pass
     
     def DisplayAll(self):
         """Display all"""
-        print "SalomeOutsideGUI.Erase: not available outside GUI"
+        print("SalomeOutsideGUI.Erase: not available outside GUI")
         pass
     
     def EraseAll(self):
         """Erase all"""
-        print "SalomeOutsideGUI.EraseAll: not available outside GUI"
+        print("SalomeOutsideGUI.EraseAll: not available outside GUI")
         pass
 
     def IsInCurrentView(self, Entry):
         """Indicate if an entry is in current view"""
-        print "SalomeOutsideGUI.IsIncurentView: not available outside GUI"
+        print("SalomeOutsideGUI.IsIncurentView: not available outside GUI")
         return False
         
     def getComponentName(self, ComponentUserName ):
         """Get component name from component user name"""
-        print "SalomeOutsideGUI.getComponentName: not available outside GUI"
+        print("SalomeOutsideGUI.getComponentName: not available outside GUI")
         return ""
    
     def getComponentUserName( self, ComponentName ):
         """Get component user name from component name"""
-        print "SalomeOutsideGUI.getComponentUserName: not available outside GUI"
+        print("SalomeOutsideGUI.getComponentUserName: not available outside GUI")
         return ""
         
     #--------------------------------------------------------------------------
index 12ac01b8231171e5128b2972051d88d5c3e2f184..727d01df7a780b19bf68efa8e9204ea5b1f823cd 100644 (file)
@@ -36,7 +36,7 @@ class PseudoStudyForNoteBook(object):
         pass
     
     def GetVariableNames(self):
-        return self.kwargs.keys()
+        return list(self.kwargs.keys())
     
     def IsVariable(self, variableName):
         return variableName in self.kwargs
@@ -124,7 +124,7 @@ class NoteBook:
                     pass
                 try:
                     aResult = eval(aResult)
-                except Exception, e:
+                except Exception as e:
                     msg = str(e)
                     msg += "\n"
                     msg += "A problem occurs while parsing "
index 124bff168b0aa988dd8c47ab1a81a72811856791..f1b448754ef6861911f3cedebde168ad20297ca4 100644 (file)
@@ -28,7 +28,7 @@
  exception
 """
 import omniORB
-import cPickle
+import pickle
 import SALOME
 import Engines
 
@@ -38,17 +38,17 @@ class SmartPyNode(Engines._objref_PyNode):
 
   def execute(self,functionName,*args,**kws):
     try:
-      args=cPickle.dumps((args,kws),-1)
+      args=pickle.dumps((args,kws),-1)
       results=Engines._objref_PyNode.execute(self,functionName,args)
-      x=cPickle.loads(results)
+      x=pickle.loads(results)
       return x
-    except SALOME.SALOME_Exception, e:
+    except SALOME.SALOME_Exception as e:
       raise ValueError(e.details.text)
 
   def __getattr__(self,name):
     """ a trick to be able to call directly a remote method by its name : no need to use execute"""
     if name[0]== '_':
-      raise AttributeError, name
+      raise AttributeError(name)
     def afunc(*args,**kws):
       return self.execute(name,*args,**kws)
     return afunc
@@ -60,11 +60,11 @@ class SmartPyScriptNode(Engines._objref_PyScriptNode):
   def execute(self,outargsname,*args,**kws):
     #the tuple args are ignored
     try:
-      args=cPickle.dumps(((),kws),-1)
+      args=pickle.dumps(((),kws),-1)
       results=Engines._objref_PyScriptNode.execute(self,outargsname,args)
-      x=cPickle.loads(results)
+      x=pickle.loads(results)
       return x
-    except SALOME.SALOME_Exception, e:
+    except SALOME.SALOME_Exception as e:
       raise ValueError(e.details.text)
 
 #Register the new proxy for PyNode
index c084373255be678b239bc6187924f7babd1d13f5..3eda9d8fba41813e4ffdccb002d224aa7ee58def 100755 (executable)
@@ -52,7 +52,7 @@ def DumpComponent(Study, SO, Builder,offset):
     find,RefSO = CSO.ReferencedObject()
     if find:
       a=a+":"+RefSO.GetID()
-    print a
+    print(a)
     DumpComponent(Study, CSO, Builder,offset+2)
     it.Next()
 
@@ -67,7 +67,7 @@ def DumpStudy(Study):
     while itcomp.More():
       SC = itcomp.Value()
       name = SC.ComponentDataType()
-      print "-> ComponentDataType is " + name
+      print("-> ComponentDataType is " + name)
       DumpComponent(Study, SC,Builder, 1)
       itcomp.Next()
 
@@ -78,7 +78,7 @@ def DumpStudies():
   global myStudyManager
   for name in myStudyManager.GetOpenStudies():
     s = myStudyManager.GetStudyByName(name)
-    print "study:",name, s._get_StudyId()
+    print("study:",name, s._get_StudyId())
     DumpStudy(s)
 
 
@@ -206,25 +206,25 @@ def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
     aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
 
     if not myStudyManager.CanCopy(theSO):
-        raise RuntimeError, "<CanCopy> for "+theInfo+" returns false"
+        raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
     
     if not myStudyManager.Copy(theSO):
-        raise RuntimeError, "<Copy> for "+theInfo+" returns false"
+        raise RuntimeError("<Copy> for "+theInfo+" returns false")
 
     
     if not myStudyManager.CanPaste(theSO):
-        raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
+        raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
 
     # check: before paste study is not changed check
     if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
-        raise RuntimeError, "Study is changed before Paste calling for "+theInfo
+        raise RuntimeError("Study is changed before Paste calling for "+theInfo)
     
     aSObj = theSO
     if theComponentPaste:
         aSObj = theSO.GetFatherComponent()
         theInfo = theInfo + "(paste for component)"
     if myStudyManager.Paste(aSObj) == None:
-        raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
+        raise RuntimeError("<Paste> for "+theInfo+" returns None object")
     aNewTree = GetTree(aRoot)
     aLen = len(aTree)
     for a in range(0,aLen):
@@ -234,7 +234,7 @@ def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
     if aLen < len(aNewTree):
         return myStudy.FindObjectID(aNewTree[aLen])
     
-    raise RuntimeError, "After Copy calling the tree is not changed"
+    raise RuntimeError("After Copy calling the tree is not changed")
     
     #--------------------------------------------------------------------------
 
@@ -289,11 +289,11 @@ def getActiveStudy(*args):
     global salome_study_ID
 
     if not myStudyManager:
-        print "No active study"
+        print("No active study")
         return None
         pass
 
-    if verbose(): print "getActiveStudy"
+    if verbose(): print("getActiveStudy")
     if salome_study_ID == -1:
         listOpenStudies = myStudyManager.GetOpenStudies()
         if len(listOpenStudies) == 0:
@@ -301,7 +301,7 @@ def getActiveStudy(*args):
         else:
             s = myStudyManager.GetStudyByName(listOpenStudies[0])
             salome_study_ID = s._get_StudyId()
-    if verbose(): print"--- Study Id ", salome_study_ID
+    if verbose(): print("--- Study Id ", salome_study_ID)
     return salome_study_ID
 
     #--------------------------------------------------------------------------
@@ -345,7 +345,7 @@ def setCurrentStudyId(*args):
     myStudyId = getActiveStudy()
     if not myStudyId:
       myStudyId = createNewStudy()
-    if verbose(): print "myStudyId",myStudyId
+    if verbose(): print("myStudyId",myStudyId)
     myStudy = myStudyManager.GetStudyByID(myStudyId)
     myStudyName = myStudy._get_Name()
     return myStudyId, myStudy, myStudyName
@@ -354,21 +354,21 @@ def setCurrentStudyId(*args):
 
 def createNewStudy():
     global myStudyManager
-    print "createNewStudy"
+    print("createNewStudy")
     aStudyName = "extStudy"
     theStudy = myStudyManager.NewStudy(aStudyName)
     theStudyId = theStudy._get_StudyId()
-    print aStudyName, theStudyId
+    print(aStudyName, theStudyId)
     return theStudyId
 
     #--------------------------------------------------------------------------
 
 def openStudy(theStudyPath):
     global myStudyManager
-    print "openStudy"
+    print("openStudy")
     theStudy = myStudyManager.Open(theStudyPath)
     theStudyId = theStudy._get_StudyId()
-    print theStudyPath, theStudyId
+    print(theStudyPath, theStudyId)
     return theStudyId
 
     #--------------------------------------------------------------------------
@@ -384,15 +384,15 @@ def salome_study_init(theStudyPath=None):
     global myStudyManager, myStudyId, myStudy, myStudyName
     global orb, lcc, naming_service, cm
 
-    if verbose(): print "theStudyPath:", theStudyPath
+    if verbose(): print("theStudyPath:", theStudyPath)
     if not myStudyManager:
         orb, lcc, naming_service, cm = salome_kernel.salome_kernel_init()
 
         # get Study Manager reference
-        if verbose(): print "looking for studyManager ..."
+        if verbose(): print("looking for studyManager ...")
         obj = naming_service.Resolve('myStudyManager')
         myStudyManager = obj._narrow(SALOMEDS.StudyManager)
-        if verbose(): print "studyManager found"
+        if verbose(): print("studyManager found")
         pass
 
     # get active study Id, ref and name
@@ -400,11 +400,11 @@ def salome_study_init(theStudyPath=None):
     myStudyId = getActiveStudy()
     if myStudyId == None :
         import types
-        if theStudyPath and type(theStudyPath) == types.StringType:
+        if theStudyPath and type(theStudyPath) == bytes:
             myStudyId = openStudy(theStudyPath)
         else:
             myStudyId = createNewStudy()
-    if verbose(): print "myStudyId", myStudyId
+    if verbose(): print("myStudyId", myStudyId)
 
     if myStudy == None:
         myStudy = myStudyManager.GetStudyByID(myStudyId)
index e0bdd983fa127d62530e3c0bf15b5bdab8894474..08070cb210dcb0fa9b8b37948d8989a141dfb34b 100755 (executable)
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-print
-print "Perform quick test of the application by loading of the GEOM, SMESH, MED, PARAVIS"
-print "components and doing some operation within the components."
-print
+print()
+print("Perform quick test of the application by loading of the GEOM, SMESH, MED, PARAVIS")
+print("components and doing some operation within the components.")
+print()
 
 import salome
 import SALOME
@@ -35,81 +35,81 @@ import SALOME_ModuleCatalog
 
 step = 1
 
-print "======================================================================"
-print "           %d. Initialize study " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Initialize study " % step); step+=1
+print("======================================================================")
 
 # initialize study
 salome.salome_init()
 # get study builder
 builder = salome.myStudy.NewBuilder()
-print "OK"
+print("OK")
 
-print 
+print() 
 
-print "======================================================================"
-print "           %d. Retrieve module catalog " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Retrieve module catalog " % step); step+=1
+print("======================================================================")
 
 obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
 catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
 if not catalog:
-    raise RuntimeError, "Can't accesss module catalog"
-print "OK"
+    raise RuntimeError("Can't accesss module catalog")
+print("OK")
 
-print
+print()
 
-print "======================================================================"
-print "           %d. Check modules availability in the module catalog " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Check modules availability in the module catalog " % step); step+=1
+print("======================================================================")
 
 for module in [ "GEOM", "SMESH", "MEDFactory", "PVSERVER"]:
-    print
-    print "--- Check %s ..." % module
+    print()
+    print("--- Check %s ..." % module)
     comp = catalog.GetComponent(module)
     if not comp:
-        raise RuntimeError, "Component %s is not found in Module Catalog." % module
-    print "OK"
+        raise RuntimeError("Component %s is not found in Module Catalog." % module)
+    print("OK")
     pass
 
-print
+print()
 
-print "======================================================================"
-print "           %d. Test Data Server " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Test Data Server " % step); step+=1
+print("======================================================================")
 
-print
-print "--- Create new component ..."
+print()
+print("--- Create new component ...")
 comp = builder.NewComponent("TEST")
 if not comp:
-    raise RuntimeError, "Can't create new component"
-print "OK"
+    raise RuntimeError("Can't create new component")
+print("OK")
 
-print
-print "--- Create AttributeName ..."
+print()
+print("--- Create AttributeName ...")
 A = builder.FindOrCreateAttribute(comp, "AttributeName")
 if not A:
-    raise RuntimeError, "Can't create AttributeName attribute"
+    raise RuntimeError("Can't create AttributeName attribute")
 A.SetValue("TEST")
 if A.Value() != "TEST":
-    raise RuntimeError, "Error : wrong value of  AttributeName"
-print "OK"
+    raise RuntimeError("Error : wrong value of  AttributeName")
+print("OK")
 
-print
-print "--- Create AttributeReal ..."
+print()
+print("--- Create AttributeReal ...")
 A = builder.FindOrCreateAttribute(comp, "AttributeReal")
 if not A:
-    raise RuntimeError, "Can't create AttributeReal attribute"
+    raise RuntimeError("Can't create AttributeReal attribute")
 A.SetValue(0.0001)
 if A.Value() != 0.0001:
-    raise RuntimeError, "Error : wrong value of  AttributeReal"
-print "OK"
+    raise RuntimeError("Error : wrong value of  AttributeReal")
+print("OK")
 
-print
+print()
 
-print "======================================================================"
-print "           %d. Test Geometry " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Test Geometry " % step); step+=1
+print("======================================================================")
 
 from salome.geom import geomBuilder
 geompy = geomBuilder.New(salome.myStudy)
@@ -122,54 +122,54 @@ ShapeTypeWire = 5
 ShapeTypeEdge = 6
 ShapeTypeVertex = 7
 
-print
-print "--- Create a box ..."
+print()
+print("--- Create a box ...")
 box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
 idbox = geompy.addToStudy(box, "box")
 box_obj = salome.myStudy.FindObjectByPath("/Geometry/box")
 if not box_obj:
-    raise RuntimeError, "Error : wrong value of  AttributeReal"
-print "OK"
+    raise RuntimeError("Error : wrong value of  AttributeReal")
+print("OK")
 
 # ---- add shell from box in study
-print 
-print "--- Extract shell ..."
+print() 
+print("--- Extract shell ...")
 subShellList = geompy.SubShapeAll(box, ShapeTypeShell)
 shell = subShellList[0]
 name = geompy.SubShapeName(shell, box)
 idshell = geompy.addToStudyInFather(box, shell, name)
-print name
-print "OK"
+print(name)
+print("OK")
 
 # ---- add first face of box in study
-print 
-print "--- Extract face ..."
+print() 
+print("--- Extract face ...")
 subShapeList = geompy.SubShapeAll(box, ShapeTypeFace)
 face = subShapeList[0]
 name = geompy.SubShapeName(face, box)
 idface = geompy.addToStudyInFather(box, face, name)
-print name
-print "OK"
+print(name)
+print("OK")
 
 # ---- add first edge of face in study
-print 
-print "--- Extract edge ..."
+print() 
+print("--- Extract edge ...")
 edgeList = geompy.SubShapeAll(face, ShapeTypeEdge)
 edge = edgeList[0];
 name = geompy.SubShapeName(edge, face)
 idedge = geompy.addToStudyInFather(face, edge, name)
-print name
-print "OK"
+print(name)
+print("OK")
 
 # ---- update object browser
 if salome.hasDesktop():
     salome.sg.updateObjBrowser(True);
 
-print
+print()
 
-print "======================================================================"
-print "           %d. Test Mesh " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Test Mesh " % step); step+=1
+print("======================================================================")
 
 from salome.StdMeshers import StdMeshersBuilder
 import SMESH
@@ -186,86 +186,86 @@ else:
 
 stdMeshersEngine = "StdMeshersEngine"
 
-print
-print "--- Create hypotheses ..."
+print()
+print("--- Create hypotheses ...")
 
-print
-print "------ LocalLength ..."
+print()
+print("------ LocalLength ...")
 hypLen1 = smesh.CreateHypothesis( "LocalLength", stdMeshersEngine )
 hypLen1.SetLength(100)
-print hypLen1.GetName()
-print hypLen1.GetId()
-print hypLen1.GetLength()
+print(hypLen1.GetName())
+print(hypLen1.GetId())
+print(hypLen1.GetLength())
 if salome.hasDesktop():
     smeshgui.SetName(salome.ObjectToID(hypLen1), "Local_Length_100")
-print "OK"
+print("OK")
 
-print
-print "------ NumberOfSegments ..."
+print()
+print("------ NumberOfSegments ...")
 hypNbSeg1= smesh.CreateHypothesis( "NumberOfSegments", stdMeshersEngine )
 hypNbSeg1.SetNumberOfSegments(7)
-print hypNbSeg1.GetName()
-print hypNbSeg1.GetId()
-print hypNbSeg1.GetNumberOfSegments()
+print(hypNbSeg1.GetName())
+print(hypNbSeg1.GetId())
+print(hypNbSeg1.GetNumberOfSegments())
 if salome.hasDesktop():
     smeshgui.SetName(salome.ObjectToID(hypNbSeg1), "NumberOfSegments_7")
-print "OK"
+print("OK")
 
-print
-print "------ MaxElementArea [1] ..."
+print()
+print("------ MaxElementArea [1] ...")
 hypArea1 = smesh.CreateHypothesis( "MaxElementArea", stdMeshersEngine )
 hypArea1.SetMaxElementArea(2500)
-print hypArea1.GetName()
-print hypArea1.GetId()
-print hypArea1.GetMaxElementArea()
+print(hypArea1.GetName())
+print(hypArea1.GetId())
+print(hypArea1.GetMaxElementArea())
 if salome.hasDesktop():
     smeshgui.SetName(salome.ObjectToID(hypArea1), "MaxElementArea_2500")
-print "OK"
+print("OK")
 
-print
-print "------ MaxElementArea [2] ..."
+print()
+print("------ MaxElementArea [2] ...")
 hypArea2 = smesh.CreateHypothesis( "MaxElementArea", stdMeshersEngine )
 hypArea2.SetMaxElementArea(500)
-print hypArea2.GetName()
-print hypArea2.GetId()
-print hypArea2.GetMaxElementArea()
+print(hypArea2.GetName())
+print(hypArea2.GetId())
+print(hypArea2.GetMaxElementArea())
 if salome.hasDesktop():
     smeshgui.SetName(salome.ObjectToID(hypArea2), "MaxElementArea_500")
-print "OK"
+print("OK")
 
 # ---- create algorithms
 
-print
-print "--- Create algorithms ..."
+print()
+print("--- Create algorithms ...")
 
-print
-print "------ Regular_1D ..."
+print()
+print("------ Regular_1D ...")
 algoReg = smesh.CreateHypothesis( "Regular_1D", stdMeshersEngine )
 listHyp = algoReg.GetCompatibleHypothesis()
 for hyp in listHyp:
-    print hyp
-print algoReg.GetName()
-print algoReg.GetId()
+    print(hyp)
+print(algoReg.GetName())
+print(algoReg.GetId())
 if salome.hasDesktop():
     smeshgui.SetName(salome.ObjectToID(algoReg), "Regular_1D" )
-print "OK"
+print("OK")
 
-print
-print "------ MEFISTO_2D ..."
+print()
+print("------ MEFISTO_2D ...")
 algoMef = smesh.CreateHypothesis( "MEFISTO_2D", stdMeshersEngine )
 listHyp=algoMef.GetCompatibleHypothesis()
 for hyp in listHyp:
-    print hyp
-print algoMef.GetName()
-print algoMef.GetId()
+    print(hyp)
+print(algoMef.GetName())
+print(algoMef.GetId())
 if salome.hasDesktop():
     smeshgui.SetName(salome.ObjectToID(algoMef), "MEFISTO_2D" )
-print "OK"
+print("OK")
 
 # ---- create mesh on the box, apply hypotheses / algorithms
 
-print
-print "--- Create mesh on the box ..."
+print()
+print("--- Create mesh on the box ...")
 mesh = smesh.CreateMesh(box)
 if salome.hasDesktop():
     smeshgui.SetName( salome.ObjectToID(mesh), "MeshBox" );
@@ -273,40 +273,40 @@ ret = mesh.AddHypothesis(box, algoReg)
 ret = mesh.AddHypothesis(box, algoMef)
 ret = mesh.AddHypothesis(box, hypNbSeg1)
 ret = mesh.AddHypothesis(box, hypArea1)
-print "OK"
+print("OK")
 
 # ---- create submesh on the edge, add hypothesis
 
-print
-print "--- Add 1D sub-mesh on the edge ..."
+print()
+print("--- Add 1D sub-mesh on the edge ...")
 submesh = mesh.GetSubMesh(edge, "SubMeshEdge")
 ret = mesh.AddHypothesis(edge, algoReg)
 ret = mesh.AddHypothesis(edge, hypLen1)
-print "OK"
+print("OK")
 
 # ---- create submesh on the edge, add hypothesis
 
-print
-print "--- Add 2D sub-mesh on the face ..."
+print()
+print("--- Add 2D sub-mesh on the face ...")
 submesh = mesh.GetSubMesh(face, "SubMeshFace")
 ret = mesh.AddHypothesis(face, hypArea2)
-print "OK"
+print("OK")
 
 # ---- compute mesh
-print
-print "--- Compute mesh ..."
+print()
+print("--- Compute mesh ...")
 smesh.Compute(mesh, box)
-print "OK"
+print("OK")
 
 # ---- update object browser
 if salome.hasDesktop():
     salome.sg.updateObjBrowser(True);
 
-print
+print()
 
-print "======================================================================"
-print "           %d. Test Med " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Test Med " % step); step+=1
+print("======================================================================")
 
 import medcalc
 #from medcalc import properties
@@ -315,7 +315,7 @@ from medcalc.fieldproxy import FieldProxy
 medcalc.medconsole.setConsoleGlobals(globals())
 try:
     med_root=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")
 
 filepath = os.path.join(med_root,"share","salome","resources","med","medcalc_testfiles","smallmesh_varfield.med")
@@ -323,35 +323,35 @@ medcalc.medio.LoadDataSource(filepath)
 fieldHandlerList = medcalc.medevents.dataManager.getFieldHandlerList()
 
 fieldHandler0 = fieldHandlerList[0]
-print "---Field Handler 0:\n%s" % fieldHandler0
+print("---Field Handler 0:\n%s" % fieldHandler0)
 fieldHandler1 = fieldHandlerList[1]
-print "---Field Handler 1:\n%s" % fieldHandler1
+print("---Field Handler 1:\n%s" % fieldHandler1)
 
-print "--- The addition of two fields can be done using field handler directly."
+print("--- The addition of two fields can be done using field handler directly.")
 addFieldHandler = medcalc.fieldproxy.calculator.add(fieldHandler0,fieldHandler1)
-print "--- Result handler:\n%s" % addFieldHandler
+print("--- Result handler:\n%s" % addFieldHandler)
 
-print "--- Or with a field proxy that easy the writing of operations."
+print("--- Or with a field proxy that easy the writing of operations.")
 fieldProxy0 = FieldProxy(fieldHandler0)
 fieldProxy1 = FieldProxy(fieldHandler1)
 
 resHandler = fieldProxy0 + fieldProxy1
 if resHandler is None:
-    print "Error: result handler is None!"
+    print("Error: result handler is None!")
 else:
-    print "--- Result handler:\n%s" % resHandler
-    print "OK"
+    print("--- Result handler:\n%s" % resHandler)
+    print("OK")
 
-print
+print()
 
 
-print "======================================================================"
-print "           %d. Test Paravis " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print("           %d. Test Paravis " % step); step+=1
+print("======================================================================")
 
 if salome.hasDesktop(): # in gui mode
 
-    print "**** Importing pvserver... It can take some time."
+    print("**** Importing pvserver... It can take some time.")
     from presentations import *
     import pvserver
     import pvsimple
@@ -360,38 +360,38 @@ if salome.hasDesktop(): # in gui mode
     
     #====================Stage1: Importing MED file====================
     
-    print "**** Stage1: Importing MED file"
+    print("**** Stage1: Importing MED file")
     
-    print 'Import "ResOK_0000.med"...............',
+    print('Import "ResOK_0000.med"...............', end=' ')
     medFileName = "ResOK_0000.med"
     medFile = os.path.join(os.getenv('DATA_DIR'), 'MedFiles', medFileName)
     pvsimple.MEDReader( FileName=medFile )
     med_reader = pvsimple.GetActiveSource()
     
     if med_reader is None:
-        print "FAILED"
+        print("FAILED")
     else:
-        print "OK"
+        print("OK")
     
     cell_entity = EntityType.CELL
     node_entity = EntityType.NODE
     
     #====================Stage2: Displaying vector field===============
     
-    print "**** Stage3: Displaying vector field"
+    print("**** Stage3: Displaying vector field")
     
-    print 'Get view...................',
+    print('Get view...................', end=' ')
     view = pvsimple.GetRenderView()
     if view is None:
-        print "FAILED"
+        print("FAILED")
     else:
         reset_view(view)
-        print "OK"
+        print("OK")
     
-    print "Creating Scalar Map.......",
+    print("Creating Scalar Map.......", end=' ')
     scalarmap = ScalarMapOnField(med_reader, node_entity, 'vitesse', 2)
     if scalarmap is None:
-        print "FAILED"
+        print("FAILED")
     else:
         bar = get_bar()
         bar.Orientation = 'Horizontal'
@@ -400,36 +400,36 @@ if salome.hasDesktop(): # in gui mode
         bar.AspectRatio = 3
         
         display_only(scalarmap, view)
-        print "OK"
+        print("OK")
     
     view.ResetCamera()
     
-    print "Creating Vectors..........",
+    print("Creating Vectors..........", end=' ')
     vectors = VectorsOnField(med_reader, node_entity, 'vitesse', 2)
     if vectors is None:
-        print "FAILED"
+        print("FAILED")
     else:
         display_only(vectors, view)
-        print "OK"
+        print("OK")
     
-    print "Creating Iso Surfaces.....",
+    print("Creating Iso Surfaces.....", end=' ')
     isosurfaces = IsoSurfacesOnField(med_reader, node_entity, 'vitesse', 2)
     if isosurfaces is None:
-        print "FAILED"
+        print("FAILED")
     else:
         display_only(isosurfaces, view)
-        print "OK"
+        print("OK")
     
-    print "Creating Cut Planes.......",
+    print("Creating Cut Planes.......", end=' ')
     cutplanes = CutPlanesOnField(med_reader, node_entity, 'vitesse', 2,
                                  nb_planes=30, orientation=Orientation.YZ)
     if cutplanes is None:
-        print "FAILED"
+        print("FAILED")
     else:
         display_only(cutplanes, view)
-        print "OK"
+        print("OK")
     
-    print "Creating Scalar Map On Deformed Shape.......",
+    print("Creating Scalar Map On Deformed Shape.......", end=' ')
     scalarmapondefshape = DeformedShapeAndScalarMapOnField(med_reader,
                                                            node_entity,
                                                            'vitesse', 2,
@@ -437,17 +437,17 @@ if salome.hasDesktop(): # in gui mode
                                                            cell_entity,
                                                            'pression')
     if scalarmapondefshape is None:
-        print "FAILED"
+        print("FAILED")
     else:
         display_only(scalarmapondefshape, view)
-        print "OK"
+        print("OK")
 
 else: # not in gui mode, Paravis can not be tested
     
-    print
-    print "PARAVIS module requires SALOME to be running in GUI mode."
-    print
-    print "Skipping test for PARAVIS..."
+    print()
+    print("PARAVIS module requires SALOME to be running in GUI mode.")
+    print()
+    print("Skipping test for PARAVIS...")
     pass
 
 # ---- update object browser
index a17424a15b05beb87c8ae8d93d6a778953c558b2..1642ed9a7a4f1b9da943ef08785b8c8510d7a11c 100644 (file)
@@ -49,7 +49,7 @@ def getVersion( mod = "KERNEL", full = False ):
     global _salome_versions
     mod = mod.upper()
     dev_flag = { True : "dev", False : "" }
-    if not _salome_versions.has_key( mod ):
+    if mod not in _salome_versions:
         _salome_versions[ mod ] = [ None, "" ]
         import os
         root_dir = os.getenv( "%s_ROOT_DIR" % mod )
index 23855be65e3d1c05831dcecbec45c248c8667eb2..c94b5d55c5360aafacf9904c5f57237773e43b78 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import setenv
index 53fe67af54fff949a236ac2290915f7f8255a1be..2b9ee1583e92ab6e0414e84d5b6e74ddabc7750e 100755 (executable)
@@ -46,7 +46,7 @@ class TestCompo(unittest.TestCase):
       text = f.read()
       f.close()
       self.assertEqual(text, content)
-    except IOError,ex:
+    except IOError as ex:
       self.fail("IO exception:" + str(ex));
 
   ##############################
@@ -95,7 +95,7 @@ f.close()
     launcher = salome.naming_service.Resolve('/SalomeLauncher')
     
     for resource in self.ressources:
-      print "Testing python_salome job on ", resource
+      print("Testing python_salome job on ", resource)
       job_params.result_directory = local_result_dir + resource
       job_params.job_name = "PyJob" + resource
       job_params.resource_required.name = resource
@@ -105,11 +105,11 @@ f.close()
       launcher.launchJob(job_id)
 
       jobState = launcher.getJobState(job_id)
-      print "Job %d state: %s" % (job_id,jobState)
+      print("Job %d state: %s" % (job_id,jobState))
       while jobState != "FINISHED" and jobState != "FAILED" :
         time.sleep(5)
         jobState = launcher.getJobState(job_id)
-        print "Job %d state: %s" % (job_id,jobState)
+        print("Job %d state: %s" % (job_id,jobState))
         pass
 
       self.assertEqual(jobState, "FINISHED")
@@ -197,7 +197,7 @@ f.close()
     resManager= salome.lcc.getResourcesManager()
 
     for resource in self.ressources:
-      print "Testing command job on ", resource
+      print("Testing command job on ", resource)
       job_params.result_directory = local_result_dir + resource
       job_params.job_name = "CommandJob_" + resource
       job_params.resource_required.name = resource
@@ -212,11 +212,11 @@ f.close()
       launcher.launchJob(job_id)
       # wait for the end of the job
       jobState = launcher.getJobState(job_id)
-      print "Job %d state: %s" % (job_id,jobState)
+      print("Job %d state: %s" % (job_id,jobState))
       while jobState != "FINISHED" and jobState != "FAILED" :
         time.sleep(3)
         jobState = launcher.getJobState(job_id)
-        print "Job %d state: %s" % (job_id,jobState)
+        print("Job %d state: %s" % (job_id,jobState))
         pass
 
       # verify the results
@@ -303,7 +303,7 @@ f.close()
     resManager= salome.lcc.getResourcesManager()
     
     for resource in self.ressources:
-      print "Testing yacs job on ", resource
+      print("Testing yacs job on ", resource)
       job_params.result_directory = local_result_dir + resource
       job_params.job_name = "YacsJob_" + resource
       job_params.resource_required.name = resource
@@ -319,14 +319,14 @@ f.close()
       jobState = launcher.getJobState(job_id)
 
       yacs_dump_success = False
-      print "Job %d state: %s" % (job_id,jobState)
+      print("Job %d state: %s" % (job_id,jobState))
       while jobState != "FINISHED" and jobState != "FAILED" :
         time.sleep(5)
         jobState = launcher.getJobState(job_id)
 #        yacs_dump_success = launcher.getJobWorkFile(job_id, "dumpState_mySchema.xml",
         yacs_dump_success = launcher.getJobDumpState(job_id,
                                               job_params.result_directory)
-        print "Job %d state: %s - dump: %s" % (job_id,jobState, yacs_dump_success)
+        print("Job %d state: %s - dump: %s" % (job_id,jobState, yacs_dump_success))
         pass
 
       self.assertEqual(jobState, "FINISHED")
@@ -418,7 +418,7 @@ f.close()
     resManager= salome.lcc.getResourcesManager()
     
     for resource in self.ressources:
-      print "Testing yacs job with options on ", resource
+      print("Testing yacs job with options on ", resource)
       job_params.result_directory = local_result_dir + resource
       job_params.job_name = "YacsJobOpt_" + resource
       job_params.resource_required.name = resource
@@ -434,11 +434,11 @@ f.close()
       jobState = launcher.getJobState(job_id)
 
       yacs_dump_success = False
-      print "Job %d state: %s" % (job_id,jobState)
+      print("Job %d state: %s" % (job_id,jobState))
       while jobState != "FINISHED" and jobState != "FAILED" :
         time.sleep(5)
         jobState = launcher.getJobState(job_id)
-        print "Job %d state: %s " % (job_id,jobState)
+        print("Job %d state: %s " % (job_id,jobState))
         pass
 
       self.assertEqual(jobState, "FINISHED")
index 68d582703ab2e577705855d6cc5a6b4c9f954807..6d52cebcefc6ea40cdfaecfc4def2d00f076c90a 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import setenv
index 6690b5193f8c09ce55e41957d3713d6083da62c1..303d2cc1b00ec23a614ec11e73dc21c81e22244b 100644 (file)
@@ -177,7 +177,7 @@ class LifeCycleCORBA_SWIGTest(unittest.TestCase):
         containerName += "/swTheContainer"
         try:
             cp1=self.lcc.FindOrLoad_Component(containerName,"SalomeTestComponent")
-        except RuntimeError,ex :
+        except RuntimeError as ex :
             self.assertEqual(ex.args[0],'unknown host')
         pass
 
index 36f2a570c3bf40df4c8efd1f354ad085e14c364b..073af7047a5c47501457d7986249eda5e32603f1 100644 (file)
@@ -26,7 +26,7 @@
 #  Module : SALOME
 #  $Header$
 #
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import setenv
index 878797b5b06a387ec47aeb27e96c98a59afdda19..2f7d481cddb0475c42b53a78056fda012b50f24a 100644 (file)
@@ -44,7 +44,7 @@ try :
     engine=lcc.FindComponent(param,'SalomeTestComponent')
     engine.Coucou(1)
 except :
-    print 'lcc.FindOrLoad_Component("FactoryServer","SalomeTestComponent") failed'
+    print('lcc.FindOrLoad_Component("FactoryServer","SalomeTestComponent") failed')
 
 import sys
 import CORBA
@@ -71,7 +71,7 @@ try :
     engineCPP=lcc.FindComponent(myContainerparamsCPP,'SalomeTestComponent')
     engineCPP.Coucou(1)
 except :
-    print 'ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) C++ failed'
+    print('ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) C++ failed')
 
 try :
     myContainerparamsPy = LifeCycleCORBA.ContainerParameters()
@@ -85,5 +85,5 @@ try :
     enginePy=lcc.FindComponent(myContainerparamsPy,'SALOME_TestComponentPy')
     enginePy.Coucou(1)
 except :
-    print 'ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed'
+    print('ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed')
 
index 2f80c10c134976eb33469904cbcb1932b829bce9..ecfef6ab9b6739583c501e21a57ca58473ddb167 100644 (file)
@@ -81,10 +81,10 @@ omniORBpyAPI* api;
   if (!omnipy)
   {
     PyErr_SetString(PyExc_ImportError, (char*)"Cannot import _omnipy");
-    return;
+    return NULL;
   }
   PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
-  api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
+  api = (omniORBpyAPI*)PyCapsule_New(pyapi,NULL,NULL);
   Py_DECREF(pyapi);
 %}
 
index f2cc791a38647dc4d7c8d401a7a1da9f80136e69..faf4c342153d6090f4589e0cde28b5da83937620 100644 (file)
@@ -33,7 +33,7 @@ import time
 import os
 
 trace="local"
-if (os.environ.has_key("SALOME_trace")):
+if ("SALOME_trace" in os.environ):
   if (os.environ["SALOME_trace"] == "with_logger"):
     trace="logger"
 
@@ -57,22 +57,22 @@ class SALOME_Trace :
                 if not self.m_pInterfaceLogger is None:
                   ok = 1
 
-              except CosNaming.NamingContext.NotFound, e :
-                    if steps == 1: print "Caught exception: Naming Service can't found Logger"
+              except CosNaming.NamingContext.NotFound as e :
+                    if steps == 1: print("Caught exception: Naming Service can't found Logger")
               except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
-                    if steps == 1: print "Caught CORBA::SystemException CommFailure"
-              except CORBA.SystemException, e:
-                    if steps == 1: print "Caught CORBA::SystemException."
-              except CORBA.Exception, e:
-                    if steps == 1: print "Caught CORBA::Exception."
-              except Exception, e:
-                    if steps == 1: print "Caught unknown exception."
+                    if steps == 1: print("Caught CORBA::SystemException CommFailure")
+              except CORBA.SystemException as e:
+                    if steps == 1: print("Caught CORBA::SystemException.")
+              except CORBA.Exception as e:
+                    if steps == 1: print("Caught CORBA::Exception.")
+              except Exception as e:
+                    if steps == 1: print("Caught unknown exception.")
 
               time.sleep(0.25)
               steps = steps - 1
 
     def putMessage ( self, LogMsg ) :
         if (CORBA.is_nil(self.m_pInterfaceLogger)):
-            print  LogMsg;
+            print(LogMsg);
         else:
             self.m_pInterfaceLogger.putMessage (LogMsg)
index a05bfd39af6bed524d68baa6378c2e69ee291d4d..7a41210acd8e81d49824210fadc050022b33925a 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 
 def getCurrentPort():
     fic=os.environ['OMNIORB_CONFIG']
@@ -35,7 +35,7 @@ def closeSalome():
     port = getCurrentPort()
     try:
         from PortManager import releasePort
-        print "### release current port:", port
+        print("### release current port:", port)
         releasePort(port)
     except:
         pass
@@ -50,12 +50,12 @@ def killNamingService():
     """
     port = getCurrentPort()
     command='ps -eo pid,command | grep "omniNames -start '+str(port)+'" | grep --invert-match grep'
-    output_com = commands.getoutput(command)
+    output_com = subprocess.getoutput(command)
     try:
       pid=string.split(output_com)[0]
       os.kill(int(pid),signal.SIGKILL)
     except:
-      print "killNamingService failed."
+      print("killNamingService failed.")
 
 
 def killProcess(process_id):
@@ -64,12 +64,12 @@ def killProcess(process_id):
     generated by runSalome.Server() class and derived, (method run).
     kills also local Naming server.
     """
-    for pid, cmd in process_id.items():
-        print "stop process %s : %s"% (pid, cmd[0])
+    for pid, cmd in list(process_id.items()):
+        print("stop process %s : %s"% (pid, cmd[0]))
         try:
             os.kill(int(pid),signal.SIGKILL)
         except:
-            print "  ---- process %s : %s inexistant"% (pid, cmd[0])
+            print("  ---- process %s : %s inexistant"% (pid, cmd[0]))
             pass
         del process_id[pid]
         pass
index ddda604a465bacadb00a44df7fbf701941e9b5eb..86fc22b16756130d10e2ee7e9a434d4d47df48c1 100644 (file)
@@ -202,7 +202,7 @@ bool Engines_MPIContainer_i::Lload_component_Library(const char* componentName)
       PyObject *result = PyObject_CallMethod(pyCont,
                                              (char*)"import_component",
                                              (char*)"s",componentName);
-      std::string ret= PyString_AsString(result);
+      std::string ret= PyUnicode_AsUTF8(result);
       SCRUTE(ret);
       Py_RELEASE_NEW_THREAD;
   
index 9e89c6a6dedd52e4a6778387c045dfc331b6dbe2..de3c69a6acd823fe1f134d265bbe9bbb8d011940 100755 (executable)
 import batchmode_salome
 import SALOME_ModuleCatalog
 
-print
-print "======================================================================"
-print "           XML Catalog file generation from idl file"
-print "======================================================================"
+print()
+print("======================================================================")
+print("           XML Catalog file generation from idl file")
+print("======================================================================")
 
 import os
 os.system('runIDLparser -Wbcatalog=x \
                  ${KERNEL_ROOT_DIR}/idl/salome/SALOME_TestModuleCatalog.idl')
 
-print "======================================================================"
-print "           Get Catalog "
-print "======================================================================"
+print("======================================================================")
+print("           Get Catalog ")
+print("======================================================================")
 obj = batchmode_salome.naming_service.Resolve('Kernel/ModulCatalog')
 catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
 catalog.GetComponentList()
 
-print 
-print "======================================================================"
-print "           Import xml file "
-print "======================================================================"
+print() 
+print("======================================================================")
+print("           Import xml file ")
+print("======================================================================")
 catalog.ImportXmlCatalogFile("x.xml")
 
 name = "AddComponent"
-print 
-print "======================================================================"
-print "           Dump component <", name, "> "
-print "======================================================================"
+print() 
+print("======================================================================")
+print("           Dump component <", name, "> ")
+print("======================================================================")
 C = catalog.GetComponent(name)
 
-print "name       : ", C._get_componentname()
-print "username   : ", C._get_componentusername()
-print "type       : ", C._get_component_type()
-print "constraint : ", C._get_constraint()
-print "icon       : ", C._get_component_icone()
+print("name       : ", C._get_componentname())
+print("username   : ", C._get_componentusername())
+print("type       : ", C._get_component_type())
+print("constraint : ", C._get_constraint())
+print("icon       : ", C._get_component_icone())
 
 for iL in C.GetInterfaceList():
     I = C.GetInterface(iL)
-    print "interface  : ", I.interfacename
+    print("interface  : ", I.interfacename)
     for S in I.interfaceservicelist:
-        print "  service : ", S.ServiceName
-        print "    ", len(S.ServiceinParameter), "in params : "
+        print("  service : ", S.ServiceName)
+        print("    ", len(S.ServiceinParameter), "in params : ")
         for iP in S.ServiceinParameter:
-            print '      ' + iP.Parametername + '(' + iP.Parametertype + ')'
+            print('      ' + iP.Parametername + '(' + iP.Parametertype + ')')
             pass
-        print "    ", len(S.ServiceoutParameter), "out params : "
+        print("    ", len(S.ServiceoutParameter), "out params : ")
         for iP in S.ServiceoutParameter:
-            print '      ' + iP.Parametername + '(' + iP.Parametertype + ')'
+            print('      ' + iP.Parametername + '(' + iP.Parametertype + ')')
             pass
-        print "    ", len(S.ServiceinDataStreamParameter), "in datastream params : "
+        print("    ", len(S.ServiceinDataStreamParameter), "in datastream params : ")
         for iP in S.ServiceinDataStreamParameter:
-            print '      ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
-                  str(iP.Parameterdependency) + ')'
+            print('      ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
+                  str(iP.Parameterdependency) + ')')
             pass
-        print "    ", len(S.ServiceoutDataStreamParameter), "out datastream params : "
+        print("    ", len(S.ServiceoutDataStreamParameter), "out datastream params : ")
         for iP in S.ServiceoutDataStreamParameter:
-            print '      ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
-                  str(iP.Parameterdependency) + ')'
+            print('      ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
+                  str(iP.Parameterdependency) + ')')
             pass
         pass
     pass
index 0f2ab825d22cc68f57ff36b8c9cad02ea9bb32ca..bc10283c5c9b2cf78b54847d32b4d6658b75b4b3 100644 (file)
@@ -68,7 +68,7 @@ def getParamValue( param_name, default_value, args ):
 # print error message
 #--------------------------------------------------
 def error (message):
-    print "ERROR : ", message
+    print("ERROR : ", message)
 
 
 #--------------------------------------------------
@@ -119,7 +119,7 @@ class Tree:
         if self.name != '':
             s = string.ljust('', 4*depth)
             s += '<' + self.name
-            for k,v in self.attrs.items():
+            for k,v in list(self.attrs.items()):
               s += ' ' + k + '="' + v + '"'
             s += '>'
             if self.content != '':
@@ -145,7 +145,7 @@ class Tree:
         if levels == 0: return
 
         s = string.ljust('', 4*depth)
-        print s, self, self.content
+        print(s, self, self.content)
         for i in self.childs:
             i.Dump(levels-1, depth+1)
 
@@ -296,8 +296,7 @@ def parseComment(comment):
             ## the remaining part of input string
             m = re.match(pattern, sPorts)
             if m is None:
-                raise LookupError, \
-                      'format error in DataStreamPort definition : '+sPorts
+                raise LookupError('format error in DataStreamPort definition : '+sPorts)
             sPorts = sPorts[m.end():]
             result.append(m.groups())
 
@@ -402,9 +401,8 @@ class Interface(Tree):
             if type == 'DataStreamPorts':
                 Service = self.findService(key)
                 if Service is None:
-                    raise LookupError, \
-                          'service ' + key + \
-                          ' not found in interface : ' + self.key
+                    raise LookupError('service ' + key + \
+                          ' not found in interface : ' + self.key)
                 for p in result:
                 ## process next DataStreamPort
                     Service.createDataStreamParameter(p)
@@ -503,14 +501,14 @@ class Catalog(ContentHandler, Tree):
         complist = self.getNode('component-list')
         idx = 0
         if complist is None:
-            print "Catalog.removeComponent() : 'component-list' is not found"
+            print("Catalog.removeComponent() : 'component-list' is not found")
             return
         for comp in complist.childs:
             cname = comp.getChild('component-name')
             if cname is not None:
                 if cname.content == name:
                     complist.childs.pop(idx)
-                    print "Component " + name + " is removed"
+                    print("Component " + name + " is removed")
             idx += 1
 
     def startDocument(self):
@@ -571,10 +569,10 @@ class Catalog(ContentHandler, Tree):
                 break;
 
         if present == 0:
-            print '   add component', i_ext.getChild('component-name').content
+            print('   add component', i_ext.getChild('component-name').content)
             L_int.addChild(i_ext)
         else:
-            print '   replace component', i_ext.getChild('component-name').content
+            print('   replace component', i_ext.getChild('component-name').content)
             i_int.merge(i_ext)
 
     def mergeType(self, type):
@@ -836,20 +834,20 @@ def run(tree, args):
     common_data["COMP_MULT"]  = getParamValue("multistudy", "1",               args)
     common_data["COMP_IMPL"]  = getParamValue("impltype",   "1",               args)
 
-    print common_data
+    print(common_data)
 
     remove_comp = getParamValue("remove", "", args)
 
     #==================================================
 
     if (os.path.exists(CatalogFileName)):
-        print "Importing", CatalogFileName
+        print("Importing", CatalogFileName)
         C = Catalog(CatalogFileName)
     else:
-        print "Creating ",CatalogFileName
+        print("Creating ",CatalogFileName)
         C = Catalog()
 
-    print "Reading idl file"
+    print("Reading idl file")
 
     visitor = ModuleCatalogVisitor(C)
     tree.accept(visitor)
@@ -860,12 +858,12 @@ def run(tree, args):
         C.removeComponent(remove_comp)
 
     if (os.path.exists(CatalogFileName)):
-        print "Updating", CatalogFileName
+        print("Updating", CatalogFileName)
         CatalogFileName_old = CatalogFileName + '_old'
         os.rename(CatalogFileName, CatalogFileName_old)
     else:
         CatalogFileName_old = ""
-        print "Writing", CatalogFileName
+        print("Writing", CatalogFileName)
 
     CatalogFileName_new = CatalogFileName + '_new'
     f=open(CatalogFileName_new, 'w')
@@ -877,10 +875,10 @@ def run(tree, args):
     if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
         os.unlink(CatalogFileName_old)
 
-    print
+    print()
 
 
 if __name__ == "__main__":
-    print
-    print "Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,multistudy=<component_multistudy>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>"
-    print
+    print()
+    print("Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,multistudy=<component_multistudy>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>")
+    print()
index 4233797e604932acc97dd278049b9993dfc1ef26..7ca7f90fdbbb5b5b27db56aad2a105cc4802a58c 100644 (file)
@@ -101,7 +101,7 @@ class SALOME_NamingServicePy_i(object):
             #delete first '/' before split
             Path=Path[1:]
 
-        result_resolve_path = string.split(Path,'/')
+        result_resolve_path = Path.split('/')
         if len(result_resolve_path)>1:
             # A directory is treated (not only an object name)
             # We had to test if the directory where ObjRef should be recorded 
@@ -114,11 +114,11 @@ class SALOME_NamingServicePy_i(object):
             try:
                 obj = self._current_context.resolve(_context_name)
                 self._current_context = obj._narrow(CosNaming.NamingContext)
-            except CosNaming.NamingContext.NotFound, ex:
+            except CosNaming.NamingContext.NotFound as ex:
                 _not_exist = 1
-            except CosNaming.NamingContext.InvalidName, ex:
+            except CosNaming.NamingContext.InvalidName as ex:
                 MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )
-            except CosNaming.NamingContext.CannotProceed, ex:
+            except CosNaming.NamingContext.CannotProceed as ex:
                 MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )
             except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
                 MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
@@ -133,7 +133,7 @@ class SALOME_NamingServicePy_i(object):
                     try:
                         obj = self._current_context.resolve(_context_name)
                         self._current_context = obj._narrow(CosNaming.NamingContext)
-                    except CosNaming.NamingContext.NotFound, ex:
+                    except CosNaming.NamingContext.NotFound as ex:
                         #This context is not created. It will be done
                         self._current_context = self._current_context.bind_new_context(_context_name)
 
@@ -143,13 +143,13 @@ class SALOME_NamingServicePy_i(object):
         _context_name = [CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")]
         try:
             self._current_context.bind(_context_name,ObjRef)
-        except CosNaming.NamingContext.NotFound, ex:
+        except CosNaming.NamingContext.NotFound as ex:
             MESSAGE ( "Register : CosNaming.NamingContext.NotFound" )
-        except CosNaming.NamingContext.InvalidName, ex:
+        except CosNaming.NamingContext.InvalidName as ex:
             MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )
-        except CosNaming.NamingContext.CannotProceed, ex:
+        except CosNaming.NamingContext.CannotProceed as ex:
             MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )
-        except CosNaming.NamingContext.AlreadyBound, ex:
+        except CosNaming.NamingContext.AlreadyBound as ex:
             MESSAGE ( "Register : CosNaming.NamingContext.AlreadyBound, object will be rebind" )
             self._current_context.rebind(_context_name,ObjRef)
         except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
@@ -169,20 +169,20 @@ class SALOME_NamingServicePy_i(object):
             #delete first '/' before split
             Path=Path[1:]
 
-        result_resolve_path = string.split(Path,'/')
+        result_resolve_path = Path.split('/')
         _context_name=[]
         for i in range(len(result_resolve_path)-1):
             _context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))
         _context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object"))
         try:
             self._obj = self._current_context.resolve(_context_name)
-        except CosNaming.NamingContext.NotFound, ex:
+        except CosNaming.NamingContext.NotFound as ex:
             MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" )
             self._obj = None
-        except CosNaming.NamingContext.InvalidName, ex:
+        except CosNaming.NamingContext.InvalidName as ex:
             MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" )
             self._obj = None
-        except CosNaming.NamingContext.CannotProceed, ex:
+        except CosNaming.NamingContext.CannotProceed as ex:
             MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" )
             self._obj = None
         except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
@@ -206,18 +206,18 @@ class SALOME_NamingServicePy_i(object):
             #delete first '/' before split
             Path=Path[1:]
 
-        result_resolve_path = string.split(Path,'/')
+        result_resolve_path = Path.split('/')
         _context_name = []
         for i in range(len(result_resolve_path)):
             _context_name[CosNaming.NameComponent(result_resolve_path[i],"dir")]            
             try:
                 obj = self._current_context.resolve(_context_name)
                 self._current_context = obj._narrow(CosNaming.NamingContext)
-            except CosNaming.NamingContext.NotFound, ex:
+            except CosNaming.NamingContext.NotFound as ex:
                 self._current_context = self._current_context.bind_new_context(_context_name)
-            except CosNaming.NamingContext.InvalidName, ex:
+            except CosNaming.NamingContext.InvalidName as ex:
                 MESSAGE ( "Create_Directory : CosNaming.NamingContext.InvalidName" )
-            except CosNaming.NamingContext.CannotProceed, ex:
+            except CosNaming.NamingContext.CannotProceed as ex:
                 MESSAGE ( "Create_Directory : CosNaming.NamingContext.CannotProceed" )
             except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
                 MESSAGE ( "Create_Directory : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
@@ -227,7 +227,7 @@ class SALOME_NamingServicePy_i(object):
 
         remove a name in naming service
       """
-      resolve_path=string.split(Path,'/')
+      resolve_path=Path.split('/')
       if resolve_path[0] == '': del resolve_path[0]
       dir_path=resolve_path[:-1]
       context_name=[]
@@ -237,9 +237,9 @@ class SALOME_NamingServicePy_i(object):
       
       try:
         self._root_context.unbind(context_name)
-      except CosNaming.NamingContext.NotFound, ex:
+      except CosNaming.NamingContext.NotFound as ex:
         return
-      except CORBA.Exception,ex:
+      except CORBA.Exception as ex:
         return
 
     def Destroy_FullDirectory(self,Path):
@@ -248,15 +248,15 @@ class SALOME_NamingServicePy_i(object):
         remove recursively a directory
       """
       context_name=[]
-      for e in string.split(Path,'/'):
+      for e in Path.split('/'):
         if e == '':continue
         context_name.append(CosNaming.NameComponent(e,"dir"))
 
       try:
         context=self._root_context.resolve(context_name)
-      except CosNaming.NamingContext.NotFound, ex:
+      except CosNaming.NamingContext.NotFound as ex:
         return
-      except CORBA.Exception,ex:
+      except CORBA.Exception as ex:
         return
 
       bl,bi=context.list(0)
index 51fe25b2d9aed6295c204cc340ca9c8b827089db..e8c2a82031c7c06f8f8dadf388debbdf204cdf30 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import setenv
index 25267d785900ccbea38f0679002e48456c3ffc60..14ae2c2325197dea64c7473d692fd7a05255b824 100644 (file)
@@ -216,7 +216,7 @@ Container_proxy_impl_final::load_component_Library(const char* componentName, CO
       PyObject *result = PyObject_CallMethod(pyCont,
                                              (char*)"import_component",
                                              (char*)"s",componentName);
-      std::string ret_p= PyString_AsString(result);
+      std::string ret_p= PyUnicode_AsUTF8(result);
       Py_XDECREF(result);
       Py_RELEASE_NEW_THREAD;
 
index 14a6129349da0061d327af399049a825514c9e4f..313de06869345ab5ad92a64b403d7cdda8951f3d 100644 (file)
@@ -353,7 +353,7 @@ Engines_Parallel_Container_i::load_component_Library(const char* componentName,
     PyObject *result = PyObject_CallMethod(pyCont,
                                            (char*)"import_component",
                                            (char*)"s",componentName);
-    std::string ret_p= PyString_AsString(result);
+    std::string ret_p= PyUnicode_AsUTF8(result);
     Py_XDECREF(result);
     Py_RELEASE_NEW_THREAD;
 
index 863a12eabb44cdf7631d7f3746af8f043377a4c8..2551d4bdbb4e66fc820ee1647761d82ce1f8729c 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import orbmodule
index df3697b5be490b47abc57426fa8fe6aca9471f15..0b0daf2bd3fb1abdb09dac4e0f2992c95d9398b4 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import orbmodule
index 436af9931b5d18378a379a25b9462e747bef0be7..3c621ee5be14fe4332fdf84001a1b2a2712130bd 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, signal,string,commands
+import sys, signal,string,subprocess
 import subprocess
 import runSalome
 import setenv
index d3bc1061908993f07094b4c669c4868563d91803..9d8a641fc149c96af4f21d679795f5f9eef3514c 100644 (file)
@@ -21,7 +21,7 @@
 
 # dict,list,tuple,int,float,str
 import SALOME
-import cPickle
+import pickle
 
 class List(object):
     def __init__(self,varPtr,isTemporaryVar=False):
@@ -37,7 +37,7 @@ class List(object):
         pass
 
     def assign(self,elt):
-        st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+        st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
         self._var_ptr.setSerializedContent(st)
         pass
 
@@ -60,7 +60,7 @@ class List(object):
         return self.local_copy().__repr__()
 
     def local_copy(self):
-        return cPickle.loads(self._var_ptr.fetchSerializedContent())
+        return pickle.loads(self._var_ptr.fetchSerializedContent())
 
     def __reduce__(self):
         return (list,(self.local_copy(),))
@@ -81,7 +81,7 @@ class Tuple(object):
         pass
 
     def assign(self,elt):
-        st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+        st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
         self._var_ptr.setSerializedContent(st)
         pass
 
@@ -100,7 +100,7 @@ class Tuple(object):
         return self.local_copy().__repr__()
 
     def local_copy(self):
-        return cPickle.loads(self._var_ptr.fetchSerializedContent())
+        return pickle.loads(self._var_ptr.fetchSerializedContent())
 
     def __reduce__(self):
         return (tuple,(self.local_copy(),))
@@ -130,7 +130,7 @@ class Int(object):
         return ret(*args)
 
     def assign(self,elt):
-        st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+        st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
         self._var_ptr.setSerializedContent(st)
         pass
 
@@ -141,7 +141,7 @@ class Int(object):
         return self.local_copy().__repr__()
 
     def local_copy(self):
-        return cPickle.loads(self._var_ptr.fetchSerializedContent())
+        return pickle.loads(self._var_ptr.fetchSerializedContent())
 
     def __reduce__(self):
         return (int,(self.local_copy(),))
@@ -162,7 +162,7 @@ class Dict(object):
         pass
 
     def assign(self,elt):
-        st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+        st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
         self._var_ptr.setSerializedContent(st)
         pass
 
@@ -184,7 +184,7 @@ class Dict(object):
         return self.local_copy().__repr__()
 
     def local_copy(self):
-        return cPickle.loads(self._var_ptr.fetchSerializedContent())
+        return pickle.loads(self._var_ptr.fetchSerializedContent())
 
     def __reduce__(self):
         return (dict,(self.local_copy(),))
@@ -199,14 +199,14 @@ class Caller:
         pass
 
     def __call__(self,*args):
-        ret=self._var_ptr.invokePythonMethodOn(self._meth,cPickle.dumps(args,cPickle.HIGHEST_PROTOCOL))
+        ret=self._var_ptr.invokePythonMethodOn(self._meth,pickle.dumps(args,pickle.HIGHEST_PROTOCOL))
         return GetHandlerFromRef(ret,True)
     pass
 
 PyHandlerTypeMap={int:Int,list:List,tuple:Tuple,dict:Dict}
 
 def GetHandlerFromRef(objCorba,isTempVar=False):
-    v=cPickle.loads(objCorba.fetchSerializedContent())
+    v=pickle.loads(objCorba.fetchSerializedContent())
     if v is None:
         return None
     return PyHandlerTypeMap[v.__class__](objCorba,isTempVar)
index 92dae779437b24cf9b3ccfa80e2f2b559a42b5b0..7428981012514a48fdfa7ae1d2e2e3bc30546cf0 100644 (file)
@@ -230,7 +230,10 @@ void DataScopeServerBase::initializePython(int argc, char *argv[])
 {
   Py_Initialize();
   PyEval_InitThreads();
-  PySys_SetArgv(argc,argv);
+  wchar_t **changed_argv = new wchar_t*[argc]; // Setting arguments
+  for (int i = 0; i < argc; i++)
+    changed_argv[i] = Py_DecodeLocale(argv[i], NULL);
+  PySys_SetArgv(argc, changed_argv);
   PyObject *mainmod(PyImport_AddModule("__main__"));
   _globals=PyModule_GetDict(mainmod);
   if(PyDict_GetItemString(_globals, "__builtins__") == NULL)
@@ -254,8 +257,8 @@ void DataScopeServerBase::registerToSalomePiDict() const
   if(!meth)
     { Py_XDECREF(mod); return ; }
   PyObject *args(PyTuple_New(2));
-  PyTuple_SetItem(args,0,PyInt_FromLong(getpid()));
-  PyTuple_SetItem(args,1,PyString_FromString("SALOME_DataScopeServerBase"));
+  PyTuple_SetItem(args,0,PyLong_FromLong(getpid()));
+  PyTuple_SetItem(args,1,PyUnicode_FromString("SALOME_DataScopeServerBase"));
   PyObject *res(PyObject_CallObject(meth,args));
   Py_XDECREF(args);
   Py_XDECREF(res);
@@ -624,7 +627,7 @@ void DataScopeServerTransaction::pingKey(PyObject *keyObj)
           std::ostringstream oss; oss << "DataScopeServerTransaction::pingKey : for object id #" << ii << " error during cmp(k,wk[i]) !";
           throw Exception(oss.str());
         }
-      PyInt_AsLong(res);
+      PyLong_AsLong(res);
       if(PyErr_Occurred())
         {
           std::ostringstream oss; oss << "DataScopeServerTransaction::pingKey : for object id #" << ii << " error during interpretation of cmp(k,wk[i]) !";
@@ -658,7 +661,7 @@ void DataScopeServerTransaction::notifyKey(const std::string& varName, PyObject
           std::ostringstream oss; oss << "DataScopeServerTransaction::notifyKey : MAIN INTERNAL ERROR ! for object id #" << ii << " error during cmp(k,wk[i]) !";
           throw Exception(oss.str());
         }
-      long resCpp(PyInt_AsLong(res));
+      long resCpp(PyLong_AsLong(res));
       if(PyErr_Occurred())
         {
           std::ostringstream oss; oss << "DataScopeServerTransaction::notifyKey : MAIN INTERNAL ERROR ! for object id #" << ii << " error during interpretation of cmp(k,wk[i]) !";
index 7a5cd58b76ca52859aff34bcf2b04133d64e8cab..db1b19fb726a9081be1bf671c41eb39a10c13091 100644 (file)
@@ -82,7 +82,7 @@ void PickelizedPyObjRdExtServer::checkRdExtnessOf(const std::string& methodName,
       Py_XDECREF(argsPy);
       throw Exception("PickelizedPyObjRdExtServer::checkRdExtnessOf : self is NULL !");
     }
-  if(PyTuple_Check(_self)==1 || PyString_Check(_self)==1 || PyInt_Check(_self)==1 || PyBool_Check(_self)==1 || PyFloat_Check(_self)==1)
+  if(PyTuple_Check(_self)==1 || PyBytes_Check(_self)==1 || PyLong_Check(_self)==1 || PyBool_Check(_self)==1 || PyFloat_Check(_self)==1)
     return ;//_self is tuple, str, int or float -> immutable in python. So no method can break the RdExtness of _self.
   if(PyList_Check(_self)==1)
     checkListRdExtnessOf(methodName,argsPy);
index cf780a09d945bad1239c2b03ab56363cb9fc2c6e..8ffe048483d0fc476a8dabbd097138894aa895d3 100644 (file)
@@ -80,20 +80,20 @@ SALOME::PickelizedPyObjRdWrServer_ptr PickelizedPyObjRdWrServer::invokePythonMet
       if(errTyp)
         {
           PyObject *ob(PyObject_Str(errTyp));
-          oss2 << " type : \"" << (const char *)PyString_AsString(ob) << "\"";
+          oss2 << " type : \"" << (const char *)PyUnicode_AsUTF8(ob) << "\"";
           Py_XDECREF(ob); Py_XDECREF(errTyp);
         }
       if(errValue)
         {
           PyObject *ob(PyObject_Str(errValue));
-          oss2 << " value : \"" << (const char *)PyString_AsString(ob) << "\"";
+          oss2 << " value : \"" << (const char *)PyUnicode_AsUTF8(ob) << "\"";
           Py_XDECREF(ob); Py_XDECREF(errValue);
         }
       oss2 << " )";
       if(errTB)
         {
           PyObject *ob(PyObject_Str(errTB));
-          oss2 << "( traceback : \"" << (const char *)PyString_AsString(ob) << "\"";
+          oss2 << "( traceback : \"" << (const char *)PyUnicode_AsUTF8(ob) << "\"";
           Py_XDECREF(ob); Py_XDECREF(errTB);
         }
       oss2 << " )";
index 7de5f2c2b7b5433ae3acbbbfe486dae55653949d..8e219d27f335cb708c87b9863fbc0151e4e441cc 100644 (file)
@@ -111,8 +111,8 @@ SALOME::ByteVec *PickelizedPyObjServer::FromCppToByteSeq(const std::string& strT
 PyObject *PickelizedPyObjServer::GetPyObjFromPickled(const std::string& pickledData, DataScopeServerBase *dsb)
 {
   std::size_t sz(pickledData.size());
-  PyObject *pickledDataPy(PyString_FromStringAndSize(NULL,sz));// agy : do not use PyString_FromString because std::string hides a vector of byte.
-  char *buf(PyString_AsString(pickledDataPy));// this buf can be used thanks to python documentation.
+  PyObject *pickledDataPy(PyBytes_FromStringAndSize(NULL,sz));// agy : do not use PyUnicode_FromString because std::string hides a vector of byte.
+  char *buf(PyBytes_AS_STRING(pickledDataPy));// this buf can be used thanks to python documentation.
   const char *inBuf(pickledData.c_str());
   std::copy(inBuf,inBuf+sz,buf);
   PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"loads"));
@@ -133,8 +133,8 @@ PyObject *PickelizedPyObjServer::getPyObjFromPickled(const std::string& pickledD
 PyObject *PickelizedPyObjServer::GetPyObjFromPickled(const std::vector<unsigned char>& pickledData, DataScopeServerBase *dsb)
 {
   std::size_t sz(pickledData.size());
-  PyObject *pickledDataPy(PyString_FromStringAndSize(NULL,sz));// agy : do not use PyString_FromString because std::string hides a vector of byte.
-  char *buf(PyString_AsString(pickledDataPy));// this buf can be used thanks to python documentation.
+  PyObject *pickledDataPy(PyBytes_FromStringAndSize(NULL,sz));// agy : do not use PyUnicode_FromString because std::string hides a vector of byte.
+  char *buf(PyBytes_AS_STRING(pickledDataPy));// this buf can be used thanks to python documentation.
   const unsigned char *inBuf(&pickledData[0]);
   std::copy(inBuf,inBuf+sz,buf);
   PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"loads"));
@@ -156,14 +156,14 @@ std::string PickelizedPyObjServer::Pickelize(PyObject *obj, DataScopeServerBase
 {
   PyObject *args(PyTuple_New(2));
   PyTuple_SetItem(args,0,obj);
-  PyTuple_SetItem(args,1,PyInt_FromLong(2));// because "assert(cPickle.HIGHEST_PROTOCOL is 2)"
+  PyTuple_SetItem(args,1,PyLong_FromLong(2));// because "assert(cPickle.HIGHEST_PROTOCOL is 2)"
   PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"dumps"));
   PyObject *retPy(PyObject_CallObject(selfMeth,args));
   Py_XDECREF(selfMeth);
   Py_XDECREF(args);
-  std::size_t sz(PyString_Size(retPy));
+  std::size_t sz(PyBytes_Size(retPy));
   std::string ret(sz,'\0');
-  const char *buf(PyString_AsString(retPy));
+  const char *buf(PyBytes_AS_STRING(retPy));
   char *inBuf(const_cast<char *>(ret.c_str()));
   for(std::size_t i=0;i<sz;i++)
     inBuf[i]=buf[i];
@@ -184,8 +184,8 @@ void PickelizedPyObjServer::setNewPyObj(PyObject *obj)
     throw Exception("PickelizedPyObjServer::setNewPyObj : trying to assign a NULL pyobject in this !");
   if(obj==_self)
     return ;
-  if(PyList_Check(obj)==0 && PyDict_Check(obj)==0 && PyTuple_Check(obj)==0 && PyString_Check(obj)==0 && PyInt_Check(obj)==0 && PyBool_Check(obj)==0 && PyFloat_Check(obj)==0 && obj!=Py_None)
-    throw Exception("PickelizedPyObjServer::setNewPyObj : Supported python types are [list,tuple,dict,str,int,bool,float,None] !");
+  if(PyList_Check(obj)==0 && PyDict_Check(obj)==0 && PyTuple_Check(obj)==0 && PyBytes_Check(obj)==0 && PyLong_Check(obj)==0 && PyBool_Check(obj)==0 && PyFloat_Check(obj)==0 && obj!=Py_None)
+    throw Exception("PickelizedPyObjServer::setNewPyObj : Supported python types are [list,tuple,dict,bytes,int,bool,float,None] !");
   if(_self)
     {
       PyObject *selfType(PyObject_Type(_self));
index 79b12a2b24d7cf622248de89b034e3ccaeddbfdd..59de4a48305a5fe1ad9d2cc7af3dbd6f655ffff7 100644 (file)
@@ -25,9 +25,8 @@ import abc
 def _raiseNow(strCont):
     raise Exception("The method %s has been called whereas it is an interface !"%strCont)
 
-class WrappedType(object):
+class WrappedType(object, metaclass=abc.ABCMeta):
     """ Here definition of an interface in python."""
-    __metaclass__=abc.ABCMeta
     @abc.abstractmethod
     def ptr(self):
         _raiseNow("ptr")
index 9971211de54c5c88997d3e9f534940a07fa11813..854df7370c728ec4556057753f38f5f053b7ea6b 100644 (file)
@@ -20,7 +20,7 @@
 # Author : Anthony Geay
 
 import SALOME
-import cPickle
+import pickle
 import SALOMEWrappedStdType
 
 class InvokatorStyle(object):
@@ -77,7 +77,7 @@ class WrappedType(SALOMEWrappedStdType.WrappedType):
         return self._var_ptr.ptr()
 
     def local_copy(self):
-        return cPickle.loads(self._var_ptr.ptr().fetchSerializedContent())
+        return pickle.loads(self._var_ptr.ptr().fetchSerializedContent())
 
     def __str__(self):
         return self.local_copy().__str__()
@@ -91,7 +91,7 @@ class WrappedType(SALOMEWrappedStdType.WrappedType):
     def assign(self,elt):
         ptrCorba=self._var_ptr.ptr()
         assert(isinstance(ptrCorba,SALOME._objref_PickelizedPyObjRdWrServer))
-        st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+        st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
         ptrCorba.setSerializedContent(st)
         pass
 
@@ -501,7 +501,7 @@ class Caller:
         pass
 
     def __call__(self,*args):
-        ret=self._var_ptr.invokePythonMethodOn(self._meth,cPickle.dumps(args,cPickle.HIGHEST_PROTOCOL))
+        ret=self._var_ptr.invokePythonMethodOn(self._meth,pickle.dumps(args,pickle.HIGHEST_PROTOCOL))
         return GetHandlerFromRef(ret,True)
     pass
 
@@ -511,7 +511,7 @@ def GetHandlerFromRef(objCorba,isTempVar=False):
     """ Returns a client that allows to handle a remote corba ref of a global var easily.
     """
     assert(isinstance(objCorba,SALOME._objref_PickelizedPyObjServer))
-    v=cPickle.loads(objCorba.fetchSerializedContent())
+    v=pickle.loads(objCorba.fetchSerializedContent())
     if v is None:
         objCorba.UnRegister()
         return None
@@ -523,14 +523,14 @@ def CreateRdOnlyGlobalVar(value,varName,scopeName):
     salome.salome_init()
     dsm=salome.naming_service.Resolve("/DataServerManager")
     d2s,isCreated=dsm.giveADataScopeCalled(scopeName)
-    return GetHandlerFromRef(d2s.createRdOnlyVar(varName,cPickle.dumps(value,cPickle.HIGHEST_PROTOCOL)),False)
+    return GetHandlerFromRef(d2s.createRdOnlyVar(varName,pickle.dumps(value,pickle.HIGHEST_PROTOCOL)),False)
     
 def CreateRdExtGlobalVar(value,varName,scopeName):
     import salome
     salome.salome_init()
     dsm=salome.naming_service.Resolve("/DataServerManager")
     d2s,isCreated=dsm.giveADataScopeCalled(scopeName)
-    return GetHandlerFromRef(d2s.createRdExtVar(varName,cPickle.dumps(value,cPickle.HIGHEST_PROTOCOL)),False)
+    return GetHandlerFromRef(d2s.createRdExtVar(varName,pickle.dumps(value,pickle.HIGHEST_PROTOCOL)),False)
 
 def GetHandlerFromName(varName,scopeName):
     import salome
index bdbdc67616687d3a50a5c9ab49b0e0ac9a37a4ff..a4302f27cb3d5bd6f684e3d4ef48d4a48d48ee6d 100644 (file)
@@ -23,15 +23,15 @@ import SalomeSDSClt
 import SALOME
 import salome
 import unittest
-import cPickle
+import pickle
 import gc
 import time
 import multiprocessing as mp
 
 def obj2Str(obj):
-  return cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL)
+  return pickle.dumps(obj,pickle.HIGHEST_PROTOCOL)
 def str2Obj(strr):
-  return cPickle.loads(strr)
+  return pickle.loads(strr)
 def generateKey(varName,scopeName):
   dsm=salome.naming_service.Resolve("/DataServerManager")
   dss,isCreated=dsm.giveADataScopeTransactionCalled(scopeName)
@@ -51,8 +51,8 @@ def work(t):
     proc=subprocess.Popen(["python",fname],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
     out,err=proc.communicate()
     if proc.returncode!=0:
-      print out
-      print err
+      print(out)
+      print(err)
     return proc.returncode
 
 class SalomeSDSTest(unittest.TestCase):
@@ -128,7 +128,7 @@ class SalomeSDSTest(unittest.TestCase):
     #
     nbProc=8
     pool=mp.Pool(processes=nbProc)
-    asyncResult=pool.map_async(work,[(i,varName,scopeName) for i in xrange(nbProc)])
+    asyncResult=pool.map_async(work,[(i,varName,scopeName) for i in range(nbProc)])
     self.assertEqual(asyncResult.get(),nbProc*[0]) # <- the big test is here !
     dsm.removeDataScope(scopeName)
 
index ab2adb67666f8fbd4fe5e02234474c1d4c3bb9e1..c0bc4fb61c6fc90af73f0a8d7542488c6b9d1dac 100644 (file)
@@ -21,7 +21,7 @@
 
 import salome
 import SALOME
-import cPickle
+import pickle
 import gc
 import SalomeSDSClt
 
@@ -36,10 +36,10 @@ assert(isinstance(d2s,SALOME._objref_DataScopeServer))
 a=d2s.createRdWrVar("str","c")
 assert(a.getVarName()=="c")
 #
-a.setSerializedContent(cPickle.dumps(st,cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==st)
-assert(cPickle.loads(a.fetchSerializedContent())==st)
-assert(cPickle.loads(d2s.retrieveVar("c").fetchSerializedContent())==st)
+a.setSerializedContent(pickle.dumps(st,pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==st)
+assert(pickle.loads(a.fetchSerializedContent())==st)
+assert(pickle.loads(d2s.retrieveVar("c").fetchSerializedContent())==st)
 assert(isinstance(d2s.retrieveVar("c"),SALOME._objref_PickelizedPyObjRdWrServer))
 assert(dsm.listScopes()==['Default','tonyy'])
 dsm.createDataScope("S2")
@@ -53,17 +53,17 @@ a=dsm.retriveDataScope("S2").createRdWrVar("int","a")
 #
 sname="S7"
 dsm=salome.naming_service.Resolve("/DataServerManager")
-st=cPickle.dumps([],cPickle.HIGHEST_PROTOCOL)
+st=pickle.dumps([],pickle.HIGHEST_PROTOCOL)
 a=dsm.giveADataScopeCalled(sname)[0].createRdWrVar("list","a")
 dsm.giveADataScopeCalled(sname)
-a.setSerializedContent(cPickle.dumps([0,],cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==[0,])
+a.setSerializedContent(pickle.dumps([0,],pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[0,])
 a.setSerializedContent(st)
-assert(cPickle.loads(a.fetchSerializedContent())==[])
-tmp=a.invokePythonMethodOn("append",cPickle.dumps((0,),cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==[0])
-for i in xrange(0,1000):
-    tmp=a.invokePythonMethodOn("append",cPickle.dumps((i,),cPickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[])
+tmp=a.invokePythonMethodOn("append",pickle.dumps((0,),pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[0])
+for i in range(0,1000):
+    tmp=a.invokePythonMethodOn("append",pickle.dumps((i,),pickle.HIGHEST_PROTOCOL))
     pass
 dsm.removeDataScope(sname)
 #
@@ -72,7 +72,7 @@ d2s,_=dsm.giveADataScopeCalled(sname)
 d2s.createRdWrVar("list","a")
 a=SalomeSDSClt.GetHandlerFromRef(dsm.retriveDataScope(sname).retrieveVar("a"))
 a.append(1)
-for i in xrange(1000):
+for i in range(1000):
     a.append(i)
     pass
 assert(sum(a.local_copy())==499501)
index dd0c66ac5ecbff5764a66b7633010ca9cb7088f8..87065447ff12988800faedd8c0fd7a4bccde73bf 100644 (file)
@@ -1,5 +1,5 @@
 import SALOME
-import cPickle
+import pickle
 import salome
 import sys
 
@@ -9,10 +9,10 @@ scopeName="Scope1"
 varName="a"
 
 def obj2Str(obj):
-    return cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL)
+    return pickle.dumps(obj,pickle.HIGHEST_PROTOCOL)
 
 def str2Obj(strr):
-    return cPickle.loads(strr)
+    return pickle.loads(strr)
 
 def waitKey():
     dsm=salome.naming_service.Resolve("/DataServerManager")
index 9237e1995de17601a2c0d13e8f58040acdeb4d92..f703a9271fb0b3c38e6133d3afde3dbd602e2e6f 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import orbmodule
index 6025fbcec29f84ee95c5a00509c8804c7543cf98..df64656928cae9b21b8277f35cac8337b581bb97 100755 (executable)
@@ -37,13 +37,13 @@ from SALOME_ComponentPy import *
 class SALOME_TestComponentPy( Engines__POA.TestComponent, SALOME_ComponentPy_i):
 
     def Coucou(self, val):
-        print "SALOME_TestComponentPy Coucou ", val
-        result = "result from SALOME_TestComponentPy Coucou " + `val`
+        print("SALOME_TestComponentPy Coucou ", val)
+        result = "result from SALOME_TestComponentPy Coucou " + repr(val)
         return result
     
     def __init__(self, orb, poa, contID, containerName, instanceName, interfaceName):
         notif = False
         SALOME_ComponentPy_i.__init__(self, orb, poa, contID, containerName,
                                       instanceName, interfaceName, notif)
-        print "SALOME_TestComponentPy::__init__"
+        print("SALOME_TestComponentPy::__init__")
 
index 569fb0fd94df067c68fd620d02441b0af059742d..4ed27c7a358e67d1175f5992cd9865cb8b2706c2 100755 (executable)
@@ -44,7 +44,7 @@ obj = orb.resolve_initial_references("NameService")
 rootContext = obj._narrow(CosNaming.NamingContext)
 
 if rootContext is None:
-    print "Name Service Reference is invalid"
+    print("Name Service Reference is invalid")
     sys.exit(1)
 
 #resolve the name /Containers.dir/FactoryServerPy.object
@@ -56,16 +56,16 @@ name = [CosNaming.NameComponent("Containers","dir"),
 
 try:
     obj = rootContext.resolve(name)
-except CosNaming.NamingContext.NotFound, ex:
-    print  containerName , " not found in Naming Service"
+except CosNaming.NamingContext.NotFound as ex:
+    print(containerName , " not found in Naming Service")
     sys.exit(1)
 
 container = obj._narrow(Engines.Container)
-print container.getHostName()
+print(container.getHostName())
 comp = container.load_impl("SalomeTestComponent","SalomeTestComponent")
-print comp._get_instanceName()
+print(comp._get_instanceName())
 comp.ping()
 comptest = comp._narrow(Engines.TestComponent)
 if comptest is None:
-    print "probleme cast"
-print comptest.Coucou(1)
+    print("probleme cast")
+print(comptest.Coucou(1))
index 3cfc5385a80648229baa373dfd21d3efbebb473b..20bb6f49a3db547d572157d38661fc921db5362e 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import setenv
index 2d554ef642e65c8e4010ece402f28062ea7d63c1..95397b91b1636e15dc2206669d47f45ffe95bd5c 100755 (executable)
@@ -29,9 +29,9 @@ class TestEnvironment:
     salome_path = os.getenv("ROOT_SALOME", "")
     salome_context_file = os.path.join(salome_path, "salome_context.cfg")
     if not os.path.isfile(salome_context_file):
-      print "File salome_context.cfg not found."
-      print "Search path:" + salome_path
-      print "This test needs ROOT_SALOME environment variable in order to run"
+      print("File salome_context.cfg not found.")
+      print("Search path:" + salome_path)
+      print("This test needs ROOT_SALOME environment variable in order to run")
       exit(0)
     
     config_appli_text = '''<application>
@@ -40,7 +40,7 @@ class TestEnvironment:
    <module name="KERNEL" path="'''
     kernel_path = os.getenv("KERNEL_ROOT_DIR", "")
     if not os.path.isdir(kernel_path) :
-      print "KERNEL_ROOT_DIR not defined"
+      print("KERNEL_ROOT_DIR not defined")
       exit(0)
       pass
     
@@ -74,7 +74,7 @@ class TestEnvironment:
     self.salome_module = imp.load_source("SALOME", os.path.join(appli_dir, "salome"))
     try:
       self.salome_module.main(["start", "-t"])
-    except SystemExit, e:
+    except SystemExit as e:
       # There is an exit() call in salome.main. Just ignore it.
       pass
     
@@ -82,7 +82,7 @@ class TestEnvironment:
     ret = 0
     try:
       ret = self.salome_module.main(["shell", script])
-    except SystemExit, e:
+    except SystemExit as e:
       # return exit value
       ret = e.code
     return ret
@@ -90,7 +90,7 @@ class TestEnvironment:
   def tearDown(self):
     try:
       self.salome_module.main(["killall"])
-    except SystemExit, e:
+    except SystemExit as e:
       pass
     pass
   pass #class TestEnvironment
index 28ee924ce1fe70f3081aee1934488d9e56e58f85..ec38d52d2005b15263099187dcb2a4317f14e6bc 100755 (executable)
@@ -46,7 +46,7 @@ IF(NOT SALOME_LIGHT_ONLY)
     Utils_ExceptHandlers.cxx
     Utils_Mutex.cxx
   )
-  FILE(GLOB COMMON_HEADERS_HXX "${CMAKE_CURRENT_SOURCE_DIR}/*.hxx")
+  FILE(GLOB COMMON_HEADERS_HXX "${CMAKE_CURRENT_SOURCE_DIR}/*.hxx" )
   
 ELSE()
 
@@ -79,3 +79,4 @@ ADD_LIBRARY(OpUtil ${OpUtil_SOURCES})
 TARGET_LINK_LIBRARIES(OpUtil ${COMMON_LIBS})
 INSTALL(TARGETS OpUtil EXPORT ${PROJECT_NAME}TargetGroup DESTINATION ${SALOME_INSTALL_LIBS})
 INSTALL(FILES ${COMMON_HEADERS_HXX} DESTINATION ${SALOME_INSTALL_HEADERS})
+INSTALL(FILES capsulethunk.h DESTINATION ${SALOME_INSTALL_HEADERS})
index 1d51ec6699896bf6d9b6b90d1a772a443ad8637c..bae1275b62c2acca6d9d31421df9c44c882ada9e 100644 (file)
@@ -21,7 +21,7 @@
 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
 
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
 import subprocess
 import runSalome
 import orbmodule
index 0ff7f7bb099c611653ec9bab4cada94950f0123d..389174baa572c41eb3759ad26b6a09f6b07ac908 100644 (file)
@@ -49,7 +49,8 @@ def getShortHostName():
     socket.gethostname() gives short or complete Hostname, depending on
     defined aliases.
     """
-    return string.split(socket.gethostname(),'.')[0]
+    hostname = socket.gethostname()
+    return hostname.split('.')[0]
 
 class Identity:
     def __init__(self,name):
diff --git a/src/Utils/capsulethunk.h b/src/Utils/capsulethunk.h
new file mode 100644 (file)
index 0000000..6b20564
--- /dev/null
@@ -0,0 +1,134 @@
+#ifndef __CAPSULETHUNK_H
+#define __CAPSULETHUNK_H
+
+#if (    (PY_VERSION_HEX <  0x02070000) \
+     || ((PY_VERSION_HEX >= 0x03000000) \
+      && (PY_VERSION_HEX <  0x03010000)) )
+
+#define __PyCapsule_GetField(capsule, field, default_value) \
+    ( PyCapsule_CheckExact(capsule) \
+        ? (((PyCObject *)capsule)->field) \
+        : (default_value) \
+    ) \
+
+#define __PyCapsule_SetField(capsule, field, value) \
+    ( PyCapsule_CheckExact(capsule) \
+        ? (((PyCObject *)capsule)->field = value), 1 \
+        : 0 \
+    ) \
+
+
+#define PyCapsule_Type PyCObject_Type
+
+#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
+#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))
+
+
+#define PyCapsule_New(pointer, name, destructor) \
+    (PyCObject_FromVoidPtr(pointer, destructor))
+
+
+#define PyCapsule_GetPointer(capsule, name) \
+    (PyCObject_AsVoidPtr(capsule))
+
+/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
+#define PyCapsule_SetPointer(capsule, pointer) \
+    __PyCapsule_SetField(capsule, cobject, pointer)
+
+
+#define PyCapsule_GetDestructor(capsule) \
+    __PyCapsule_GetField(capsule, destructor)
+
+#define PyCapsule_SetDestructor(capsule, dtor) \
+    __PyCapsule_SetField(capsule, destructor, dtor)
+
+
+/*
+ * Sorry, there's simply no place
+ * to store a Capsule "name" in a CObject.
+ */
+#define PyCapsule_GetName(capsule) NULL
+
+static int
+PyCapsule_SetName(PyObject *capsule, const char *unused)
+{
+    unused = unused;
+    PyErr_SetString(PyExc_NotImplementedError,
+        "can't use PyCapsule_SetName with CObjects");
+    return 1;
+}
+
+
+
+#define PyCapsule_GetContext(capsule) \
+    __PyCapsule_GetField(capsule, descr)
+
+#define PyCapsule_SetContext(capsule, context) \
+    __PyCapsule_SetField(capsule, descr, context)
+
+
+static void *
+PyCapsule_Import(const char *name, int no_block)
+{
+    PyObject *object = NULL;
+    void *return_value = NULL;
+    char *trace;
+    size_t name_length = (strlen(name) + 1) * sizeof(char);
+    char *name_dup = (char *)PyMem_MALLOC(name_length);
+
+    if (!name_dup) {
+        return NULL;
+    }
+
+    memcpy(name_dup, name, name_length);
+
+    trace = name_dup;
+    while (trace) {
+        char *dot = strchr(trace, '.');
+        if (dot) {
+            *dot++ = '\0';
+        }
+
+        if (object == NULL) {
+            if (no_block) {
+                object = PyImport_ImportModuleNoBlock(trace);
+            } else {
+                object = PyImport_ImportModule(trace);
+                if (!object) {
+                    PyErr_Format(PyExc_ImportError,
+                        "PyCapsule_Import could not "
+                        "import module \"%s\"", trace);
+                }
+            }
+        } else {
+            PyObject *object2 = PyObject_GetAttrString(object, trace);
+            Py_DECREF(object);
+            object = object2;
+        }
+        if (!object) {
+            goto EXIT;
+        }
+
+        trace = dot;
+    }
+
+    if (PyCObject_Check(object)) {
+        PyCObject *cobject = (PyCObject *)object;
+        return_value = cobject->cobject;
+    } else {
+        PyErr_Format(PyExc_AttributeError,
+            "PyCapsule_Import \"%s\" is not valid",
+            name);
+    }
+
+EXIT:
+    Py_XDECREF(object);
+    if (name_dup) {
+        PyMem_FREE(name_dup);
+    }
+    return return_value;
+}
+
+#endif /* #if PY_VERSION_HEX < 0x02070000 */
+
+#endif /* __CAPSULETHUNK_H */