From dac5e4d5c8f771e0cedb7caa5292bc54be5ca89a Mon Sep 17 00:00:00 2001 From: Nicolas Geimer Date: Fri, 10 Feb 2017 16:57:29 +0100 Subject: [PATCH] [PYTHON 3] 1st draft --- bin/NSparam.py | 6 +- bin/ORBConfigFile.py | 2 +- bin/PortManager.py | 20 +- bin/addToKillList.py | 18 +- bin/appli_gen.py | 54 +-- bin/appliskel/getAppliPath.py | 4 +- bin/appliskel/kill_remote_containers.py | 4 +- bin/appliskel/salome | 6 +- bin/appliskel/salome_starter.py | 6 +- .../salome_tester/salome_instance.py | 6 +- .../salome_tester/salome_test_driver.py | 31 +- .../salome_tester/salome_test_driver_gui.py | 6 +- .../TestConcurrentSession.py | 18 +- .../concurrentSession/TestMinimalExample.py | 26 +- .../salomeCommand/TestLauncherSessionArgs.py | 4 +- .../tests/salomeCommand/TestLauncherSimple.py | 6 +- .../tests/salomeInstance/instances.py | 10 +- bin/appliskel/update_catalogs.py | 12 +- bin/killSalome.py | 10 +- bin/killSalomeWithPort.py | 32 +- bin/launchConfigureParser.py | 100 +++--- bin/nameserver.py | 10 +- bin/orbmodule.py | 52 +-- bin/parseConfigFile.py | 20 +- bin/runConsole.py | 56 +-- bin/runSalome.py | 99 +++--- bin/runSession.py | 18 +- bin/runTests.py | 2 +- bin/salomeContext.py | 185 +++++----- bin/salomeContextUtils.py.in | 6 +- bin/salome_utils.py | 16 +- bin/searchFreePort.py | 14 +- bin/server.py | 11 +- bin/setenv.py | 27 +- bin/virtual_salome.py | 51 +-- bin/waitContainers.py | 8 +- doc/salome/tui/pythfilter.py | 24 +- salome_adm/prepare_generating_doc.py | 4 +- src/AppQuickStart/app-quickstart.py | 12 +- .../app-template/src/tests/helloWorld.py | 2 +- src/Container/Container_i.cxx | 50 ++- src/Container/Container_init_python.cxx | 25 +- src/Container/SALOME_ComponentPy.py | 6 +- src/Container/SALOME_Container.py | 14 +- src/Container/SALOME_ContainerPy.py | 32 +- src/Container/SALOME_PyNode.py | 26 +- src/DSC/DSC_Python/calcium.i | 10 +- src/KERNEL_PY/Help.py | 8 +- src/KERNEL_PY/PyInterp.py | 10 +- src/KERNEL_PY/__init__.py | 12 +- src/KERNEL_PY/batchmode_salome.py | 26 +- src/KERNEL_PY/iparameters.py | 4 +- src/KERNEL_PY/kernel/__init__.py | 10 +- src/KERNEL_PY/kernel/datamodeler.py | 58 ++-- src/KERNEL_PY/kernel/diclookup.py | 28 +- src/KERNEL_PY/kernel/enumerate.py | 30 +- .../kernel/parametric/study_exchange_vars.py | 8 +- src/KERNEL_PY/kernel/pyunittester.py | 32 +- src/KERNEL_PY/kernel/services.py | 18 +- src/KERNEL_PY/kernel/studyedit.py | 12 +- src/KERNEL_PY/kernel/syshelper.py | 20 +- src/KERNEL_PY/kernel/termcolor.py | 12 +- src/KERNEL_PY/kernel/testdata.py | 30 +- src/KERNEL_PY/kernel/threadhelper.py | 72 ++-- src/KERNEL_PY/kernel/uiexception.py | 14 +- src/KERNEL_PY/kernel/unittester.py | 12 +- src/KERNEL_PY/omnipatch.py | 12 +- src/KERNEL_PY/salome_ComponentGUI.py | 4 +- src/KERNEL_PY/salome_iapp.py | 36 +- src/KERNEL_PY/salome_notebook.py | 4 +- src/KERNEL_PY/salome_pynode.py | 16 +- src/KERNEL_PY/salome_study.py | 44 +-- src/KERNEL_PY/salome_test.py | 322 +++++++++--------- src/KERNEL_PY/salome_version.py | 2 +- src/KernelHelpers/Test/TestKernelHelpers.py | 2 +- src/Launcher/Test/test_launcher.py | 26 +- src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py | 2 +- .../Test/LifeCycleCORBA_SWIGTest.py | 2 +- .../Test/TestLifeCycleCORBA_SWIG.py | 2 +- src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py | 6 +- .../libSALOME_LifeCycleCORBA.i | 4 +- src/Logger/SALOME_Trace.py | 22 +- src/Logger/Test/TestKiller.py | 14 +- src/MPIContainer/MPIContainer_i.cxx | 2 +- src/ModuleCatalog/TestModuleCatalog.py | 64 ++-- src/ModuleGenerator/IDLparser.py | 42 ++- src/NamingService/SALOME_NamingServicePy.py | 46 +-- src/NamingService/Test/TestNamingService.py | 2 +- .../SALOME_ParallelContainerProxy_i.cxx | 2 +- .../SALOME_ParallelContainer_i.cxx | 2 +- src/SALOMEDS/Test/TestSALOMEDS.py | 2 +- src/SALOMEDSImpl/Test/TestSALOMEDSImpl.py | 2 +- .../Test/TestSALOMELocalTrace.py | 2 +- src/SALOMESDS/SALOMEGlobalVarHelper.py | 22 +- src/SALOMESDS/SALOMESDS_DataScopeServer.cxx | 13 +- .../SALOMESDS_PickelizedPyObjRdExtServer.cxx | 2 +- .../SALOMESDS_PickelizedPyObjRdWrServer.cxx | 6 +- .../SALOMESDS_PickelizedPyObjServer.cxx | 18 +- src/SALOMESDS/SALOMEWrappedStdType.py | 3 +- src/SALOMESDS/SalomeSDSClt.py | 14 +- src/SALOMESDS/TestSalomeSDS.py | 12 +- src/SALOMESDS/TestSalomeSDS1.py | 28 +- src/SALOMESDS/TestSalomeSDSHelper0.py | 6 +- .../Test/TestSALOMETraceCollector.py | 2 +- src/TestContainer/SALOME_TestComponentPy.py | 6 +- src/TestContainer/TestComponentPy.py | 14 +- src/UnitTests/UnitTests.py | 2 +- src/UnitTests/prepare_test.py | 14 +- src/Utils/CMakeLists.txt | 3 +- src/Utils/Test/TestUtils.py | 2 +- src/Utils/Utils_Identity.py | 3 +- src/Utils/capsulethunk.h | 134 ++++++++ 112 files changed, 1394 insertions(+), 1173 deletions(-) create mode 100644 src/Utils/capsulethunk.h diff --git a/bin/NSparam.py b/bin/NSparam.py index 3cb3cf9cd..a9f9bdff9 100755 --- a/bin/NSparam.py +++ b/bin/NSparam.py @@ -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 # diff --git a/bin/ORBConfigFile.py b/bin/ORBConfigFile.py index 19a9647f4..a432543cc 100644 --- a/bin/ORBConfigFile.py +++ b/bin/ORBConfigFile.py @@ -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) diff --git a/bin/PortManager.py b/bin/PortManager.py index 53ebacea9..c23c28d51 100644 --- a/bin/PortManager.py +++ b/bin/PortManager.py @@ -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 diff --git a/bin/addToKillList.py b/bin/addToKillList.py index ca2abd934..685c9e979 100755 --- a/bin/addToKillList.py +++ b/bin/addToKillList.py @@ -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 diff --git a/bin/appli_gen.py b/bin/appli_gen.py index 4e04d1d32..f78d20d24 100644 --- a/bin/appli_gen.py +++ b/bin/appli_gen.py @@ -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) diff --git a/bin/appliskel/getAppliPath.py b/bin/appliskel/getAppliPath.py index b17367163..460f5c592 100755 --- a/bin/appliskel/getAppliPath.py +++ b/bin/appliskel/getAppliPath.py @@ -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) # diff --git a/bin/appliskel/kill_remote_containers.py b/bin/appliskel/kill_remote_containers.py index 06bcffb4a..4c3a39429 100755 --- a/bin/appliskel/kill_remote_containers.py +++ b/bin/appliskel/kill_remote_containers.py @@ -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__': diff --git a/bin/appliskel/salome b/bin/appliskel/salome index 171036b0e..e14ccae28 100755 --- a/bin/appliskel/salome +++ b/bin/appliskel/salome @@ -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) diff --git a/bin/appliskel/salome_starter.py b/bin/appliskel/salome_starter.py index b381b89c9..97f355e6b 100644 --- a/bin/appliskel/salome_starter.py +++ b/bin/appliskel/salome_starter.py @@ -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 diff --git a/bin/appliskel/salome_tester/salome_instance.py b/bin/appliskel/salome_tester/salome_instance.py index 8fb347e92..740138b2a 100644 --- a/bin/appliskel/salome_tester/salome_instance.py +++ b/bin/appliskel/salome_tester/salome_instance.py @@ -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() # diff --git a/bin/appliskel/salome_tester/salome_test_driver.py b/bin/appliskel/salome_tester/salome_test_driver.py index 60b8fd9a2..e4dbcd157 100644 --- a/bin/appliskel/salome_tester/salome_test_driver.py +++ b/bin/appliskel/salome_tester/salome_test_driver.py @@ -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) # diff --git a/bin/appliskel/salome_tester/salome_test_driver_gui.py b/bin/appliskel/salome_tester/salome_test_driver_gui.py index 284f9e624..777b17798 100644 --- a/bin/appliskel/salome_tester/salome_test_driver_gui.py +++ b/bin/appliskel/salome_tester/salome_test_driver_gui.py @@ -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() diff --git a/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py b/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py index 2a8a1275f..d0c066081 100644 --- a/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py +++ b/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py @@ -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() diff --git a/bin/appliskel/tests/concurrentSession/TestMinimalExample.py b/bin/appliskel/tests/concurrentSession/TestMinimalExample.py index 016453540..713f3ad96 100644 --- a/bin/appliskel/tests/concurrentSession/TestMinimalExample.py +++ b/bin/appliskel/tests/concurrentSession/TestMinimalExample.py @@ -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") # # diff --git a/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py b/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py index d6cd97541..4a9f365a0 100644 --- a/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py +++ b/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py @@ -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 diff --git a/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py b/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py index f235a0a1e..a684a6cdd 100644 --- a/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py +++ b/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py @@ -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) # diff --git a/bin/appliskel/tests/salomeInstance/instances.py b/bin/appliskel/tests/salomeInstance/instances.py index 818467736..50ecfa80d 100644 --- a/bin/appliskel/tests/salomeInstance/instances.py +++ b/bin/appliskel/tests/salomeInstance/instances.py @@ -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() # diff --git a/bin/appliskel/update_catalogs.py b/bin/appliskel/update_catalogs.py index 82fce4834..8555e0c46 100644 --- a/bin/appliskel/update_catalogs.py +++ b/bin/appliskel/update_catalogs.py @@ -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=[] diff --git a/bin/killSalome.py b/bin/killSalome.py index 2ea384b63..83111ce7a 100755 --- a/bin/killSalome.py +++ b/bin/killSalome.py @@ -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 diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py index 9670329bf..f18052e41 100755 --- a/bin/killSalomeWithPort.py +++ b/bin/killSalomeWithPort.py @@ -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 " % os.path.basename(sys.argv[0]) - print - print "Kills SALOME session running on specified ." + print("Usage: ") + print(" %s " % os.path.basename(sys.argv[0])) + print() + print("Kills SALOME session running on specified .") 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) diff --git a/bin/launchConfigureParser.py b/bin/launchConfigureParser.py index 57c492797..d819dad0f 100755 --- a/bin/launchConfigureParser.py +++ b/bin/launchConfigureParser.py @@ -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 # 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 _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 diff --git a/bin/nameserver.py b/bin/nameserver.py index f9d1a3a2c..5f806971e 100755 --- a/bin/nameserver.py +++ b/bin/nameserver.py @@ -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): diff --git a/bin/orbmodule.py b/bin/orbmodule.py index 223a91a56..81043ac11 100755 --- a/bin/orbmodule.py +++ b/bin/orbmodule.py @@ -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 diff --git a/bin/parseConfigFile.py b/bin/parseConfigFile.py index 77e6350df..63d0c92cc 100644 --- a/bin/parseConfigFile.py +++ b/bin/parseConfigFile.py @@ -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) # diff --git a/bin/runConsole.py b/bin/runConsole.py index bb2192c86..ee53a2fbf 100644 --- a/bin/runConsole.py +++ b/bin/runConsole.py @@ -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!") # diff --git a/bin/runSalome.py b/bin/runSalome.py index 33886c27f..6632e5306 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -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'] diff --git a/bin/runSession.py b/bin/runSession.py index c83ef01a1..0c5b568d4 100644 --- a/bin/runSession.py +++ b/bin/runSession.py @@ -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) diff --git a/bin/runTests.py b/bin/runTests.py index 4255abaf0..a7e8fc054 100644 --- a/bin/runTests.py +++ b/bin/runTests.py @@ -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 diff --git a/bin/salomeContext.py b/bin/salomeContext.py index 79cc1ce10..06277ee22 100644 --- a/bin/salomeContext.py +++ b/bin/salomeContext.py @@ -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 " + print("Port number(s) not provided to command: salome kill ") 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 " + print("Module(s) not provided to command: salome doc ") 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: diff --git a/bin/salomeContextUtils.py.in b/bin/salomeContextUtils.py.in index 7f9151bcf..40cd1a225 100644 --- a/bin/salomeContextUtils.py.in +++ b/bin/salomeContextUtils.py.in @@ -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 diff --git a/bin/salome_utils.py b/bin/salome_utils.py index 52a73fdd0..67c352f99 100644 --- a/bin/salome_utils.py +++ b/bin/salome_utils.py @@ -57,9 +57,9 @@ def _try_bool( arg ): If 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 diff --git a/bin/searchFreePort.py b/bin/searchFreePort.py index cdf304eba..ca2c736ea 100755 --- a/bin/searchFreePort.py +++ b/bin/searchFreePort.py @@ -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: diff --git a/bin/server.py b/bin/server.py index 75b6b16e0..3b9736323 100755 --- a/bin/server.py +++ b/bin/server.py @@ -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) diff --git a/bin/setenv.py b/bin/setenv.py index 693a51feb..0a716c849 100755 --- a/bin/setenv.py +++ b/bin/setenv.py @@ -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" diff --git a/bin/virtual_salome.py b/bin/virtual_salome.py index 3d7fbc0f9..1be8dbf8e 100755 --- a/bin/virtual_salome.py +++ b/bin/virtual_salome.py @@ -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 /bin/salome/test/ to /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 /bin/salome/test/ to /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 # ----------------------------------------------------------------------------- diff --git a/bin/waitContainers.py b/bin/waitContainers.py index 6bc37fa43..e8bf94acf 100755 --- a/bin/waitContainers.py +++ b/bin/waitContainers.py @@ -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() diff --git a/doc/salome/tui/pythfilter.py b/doc/salome/tui/pythfilter.py index 4f9439e83..cb665591f 100644 --- a/doc/salome/tui/pythfilter.py +++ b/doc/salome/tui/pythfilter.py @@ -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)) diff --git a/salome_adm/prepare_generating_doc.py b/salome_adm/prepare_generating_doc.py index dbe0153e7..b818d7af7 100755 --- a/salome_adm/prepare_generating_doc.py +++ b/salome_adm/prepare_generating_doc.py @@ -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: diff --git a/src/AppQuickStart/app-quickstart.py b/src/AppQuickStart/app-quickstart.py index 59cefd2d4..77eaaff34 100755 --- a/src/AppQuickStart/app-quickstart.py +++ b/src/AppQuickStart/app-quickstart.py @@ -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 )) # ----------------------------------------------------------------------------- diff --git a/src/AppQuickStart/app-template/src/tests/helloWorld.py b/src/AppQuickStart/app-template/src/tests/helloWorld.py index 62c813abc..44159b395 100644 --- a/src/AppQuickStart/app-template/src/tests/helloWorld.py +++ b/src/AppQuickStart/app-template/src/tests/helloWorld.py @@ -1 +1 @@ -print "Hello world" +print("Hello world") diff --git a/src/Container/Container_i.cxx b/src/Container/Container_i.cxx index b681a0124..4537accaa 100644 --- a/src/Container/Container_i.cxx +++ b/src/Container/Container_i.cxx @@ -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; +} +*/ diff --git a/src/Container/Container_init_python.cxx b/src/Container/Container_init_python.cxx index dad0be21b..42ab6eaac 100644 --- a/src/Container/Container_init_python.cxx +++ b/src/Container/Container_init_python.cxx @@ -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; } diff --git a/src/Container/SALOME_ComponentPy.py b/src/Container/SALOME_ComponentPy.py index a9ce718b8..90daef95e 100755 --- a/src/Container/SALOME_ComponentPy.py +++ b/src/Container/SALOME_ComponentPy.py @@ -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) ") #------------------------------------------------------------------------- diff --git a/src/Container/SALOME_Container.py b/src/Container/SALOME_Container.py index 2d6ee3b75..25860089d 100644 --- a/src/Container/SALOME_Container.py +++ b/src/Container/SALOME_Container.py @@ -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 #------------------------------------------------------------------------- diff --git a/src/Container/SALOME_ContainerPy.py b/src/Container/SALOME_ContainerPy.py index 4da4bacad..a9cce39d0 100755 --- a/src/Container/SALOME_ContainerPy.py +++ b/src/Container/SALOME_ContainerPy.py @@ -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") diff --git a/src/Container/SALOME_PyNode.py b/src/Container/SALOME_PyNode.py index 2feb5d4c9..62cf5906f 100644 --- a/src/Container/SALOME_PyNode.py +++ b/src/Container/SALOME_PyNode.py @@ -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() diff --git a/src/DSC/DSC_Python/calcium.i b/src/DSC/DSC_Python/calcium.i index 4a118c8e8..7f673029d 100644 --- a/src/DSC/DSC_Python/calcium.i +++ b/src/DSC/DSC_Python/calcium.i @@ -66,8 +66,8 @@ struct omniORBpyAPI { %init %{ +#include // 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"; } diff --git a/src/KERNEL_PY/Help.py b/src/KERNEL_PY/Help.py index 7948abe7f..9100c5694 100755 --- a/src/KERNEL_PY/Help.py +++ b/src/KERNEL_PY/Help.py @@ -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) diff --git a/src/KERNEL_PY/PyInterp.py b/src/KERNEL_PY/PyInterp.py index f10973927..79cec890e 100755 --- a/src/KERNEL_PY/PyInterp.py +++ b/src/KERNEL_PY/PyInterp.py @@ -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') diff --git a/src/KERNEL_PY/__init__.py b/src/KERNEL_PY/__init__.py index 84f40c655..16104045a 100755 --- a/src/KERNEL_PY/__init__.py +++ b/src/KERNEL_PY/__init__.py @@ -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(): diff --git a/src/KERNEL_PY/batchmode_salome.py b/src/KERNEL_PY/batchmode_salome.py index 7a7ae9e81..d7645f738 100755 --- a/src/KERNEL_PY/batchmode_salome.py +++ b/src/KERNEL_PY/batchmode_salome.py @@ -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, " for "+theInfo+" returns false" + raise RuntimeError(" for "+theInfo+" returns false") if not myStudyManager.Copy(theSO): - raise RuntimeError, " for "+theInfo+" returns false" + raise RuntimeError(" for "+theInfo+" returns false") if not myStudyManager.CanPaste(theSO): - raise RuntimeError, " for "+theInfo+" returns false" + raise RuntimeError(" 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, " for "+theInfo+" returns None object" + raise RuntimeError(" 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(); diff --git a/src/KERNEL_PY/iparameters.py b/src/KERNEL_PY/iparameters.py index f0b8c06a1..d3ce1c3d8 100755 --- a/src/KERNEL_PY/iparameters.py +++ b/src/KERNEL_PY/iparameters.py @@ -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""" diff --git a/src/KERNEL_PY/kernel/__init__.py b/src/KERNEL_PY/kernel/__init__.py index 1dfd4f750..65dda6ce6 100644 --- a/src/KERNEL_PY/kernel/__init__.py +++ b/src/KERNEL_PY/kernel/__init__.py @@ -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") diff --git a/src/KERNEL_PY/kernel/datamodeler.py b/src/KERNEL_PY/kernel/datamodeler.py index 9251b2a72..eec05050d 100644 --- a/src/KERNEL_PY/kernel/datamodeler.py +++ b/src/KERNEL_PY/kernel/datamodeler.py @@ -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") diff --git a/src/KERNEL_PY/kernel/diclookup.py b/src/KERNEL_PY/kernel/diclookup.py index 263e6855c..613012600 100644 --- a/src/KERNEL_PY/kernel/diclookup.py +++ b/src/KERNEL_PY/kernel/diclookup.py @@ -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") diff --git a/src/KERNEL_PY/kernel/enumerate.py b/src/KERNEL_PY/kernel/enumerate.py index e6fdff96c..5111c916f 100644 --- a/src/KERNEL_PY/kernel/enumerate.py +++ b/src/KERNEL_PY/kernel/enumerate.py @@ -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") diff --git a/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py b/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py index 0ac0490fc..4a8cfa5cd 100644 --- a/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py +++ b/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py @@ -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 diff --git a/src/KERNEL_PY/kernel/pyunittester.py b/src/KERNEL_PY/kernel/pyunittester.py index fa011080b..76e79d0ae 100644 --- a/src/KERNEL_PY/kernel/pyunittester.py +++ b/src/KERNEL_PY/kernel/pyunittester.py @@ -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) diff --git a/src/KERNEL_PY/kernel/services.py b/src/KERNEL_PY/kernel/services.py index a2d4feaa6..5e6c8db0f 100644 --- a/src/KERNEL_PY/kernel/services.py +++ b/src/KERNEL_PY/kernel/services.py @@ -38,12 +38,12 @@ # 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") diff --git a/src/KERNEL_PY/kernel/studyedit.py b/src/KERNEL_PY/kernel/studyedit.py index 463b70fb8..2b0d41e66 100644 --- a/src/KERNEL_PY/kernel/studyedit.py +++ b/src/KERNEL_PY/kernel/studyedit.py @@ -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. diff --git a/src/KERNEL_PY/kernel/syshelper.py b/src/KERNEL_PY/kernel/syshelper.py index f3c94600d..31e079fc4 100644 --- a/src/KERNEL_PY/kernel/syshelper.py +++ b/src/KERNEL_PY/kernel/syshelper.py @@ -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") diff --git a/src/KERNEL_PY/kernel/termcolor.py b/src/KERNEL_PY/kernel/termcolor.py index b7d99c778..33476f747 100644 --- a/src/KERNEL_PY/kernel/termcolor.py +++ b/src/KERNEL_PY/kernel/termcolor.py @@ -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 diff --git a/src/KERNEL_PY/kernel/testdata.py b/src/KERNEL_PY/kernel/testdata.py index 21cd9ee6a..ffbb0dcc9 100644 --- a/src/KERNEL_PY/kernel/testdata.py +++ b/src/KERNEL_PY/kernel/testdata.py @@ -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") diff --git a/src/KERNEL_PY/kernel/threadhelper.py b/src/KERNEL_PY/kernel/threadhelper.py index c71a9a543..b6d6b0689 100644 --- a/src/KERNEL_PY/kernel/threadhelper.py +++ b/src/KERNEL_PY/kernel/threadhelper.py @@ -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() diff --git a/src/KERNEL_PY/kernel/uiexception.py b/src/KERNEL_PY/kernel/uiexception.py index d1d2c8e2e..bb1928e49 100644 --- a/src/KERNEL_PY/kernel/uiexception.py +++ b/src/KERNEL_PY/kernel/uiexception.py @@ -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") diff --git a/src/KERNEL_PY/kernel/unittester.py b/src/KERNEL_PY/kernel/unittester.py index be7c3baac..dc447b6f1 100644 --- a/src/KERNEL_PY/kernel/unittester.py +++ b/src/KERNEL_PY/kernel/unittester.py @@ -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 diff --git a/src/KERNEL_PY/omnipatch.py b/src/KERNEL_PY/omnipatch.py index 1e2c0e7c6..29dd1e4f8 100644 --- a/src/KERNEL_PY/omnipatch.py +++ b/src/KERNEL_PY/omnipatch.py @@ -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__) diff --git a/src/KERNEL_PY/salome_ComponentGUI.py b/src/KERNEL_PY/salome_ComponentGUI.py index 9baeb7d5d..6afcdfa6b 100644 --- a/src/KERNEL_PY/salome_ComponentGUI.py +++ b/src/KERNEL_PY/salome_ComponentGUI.py @@ -41,12 +41,10 @@ def getShapeTypeString(aSubId): def createAndDisplayGO( *args, **kwargs ): pass - #-------------------------------------------------------------------------- def UpdateViewer(): - pass - + pass #-------------------------------------------------------------------------- def setDisplayMode(objId, mode): diff --git a/src/KERNEL_PY/salome_iapp.py b/src/KERNEL_PY/salome_iapp.py index 283c5685c..771a68a04 100755 --- a/src/KERNEL_PY/salome_iapp.py +++ b/src/KERNEL_PY/salome_iapp.py @@ -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 "" #-------------------------------------------------------------------------- diff --git a/src/KERNEL_PY/salome_notebook.py b/src/KERNEL_PY/salome_notebook.py index 12ac01b82..727d01df7 100644 --- a/src/KERNEL_PY/salome_notebook.py +++ b/src/KERNEL_PY/salome_notebook.py @@ -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 " diff --git a/src/KERNEL_PY/salome_pynode.py b/src/KERNEL_PY/salome_pynode.py index 124bff168..f1b448754 100644 --- a/src/KERNEL_PY/salome_pynode.py +++ b/src/KERNEL_PY/salome_pynode.py @@ -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 diff --git a/src/KERNEL_PY/salome_study.py b/src/KERNEL_PY/salome_study.py index c08437325..3eda9d8fb 100755 --- a/src/KERNEL_PY/salome_study.py +++ b/src/KERNEL_PY/salome_study.py @@ -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, " for "+theInfo+" returns false" + raise RuntimeError(" for "+theInfo+" returns false") if not myStudyManager.Copy(theSO): - raise RuntimeError, " for "+theInfo+" returns false" + raise RuntimeError(" for "+theInfo+" returns false") if not myStudyManager.CanPaste(theSO): - raise RuntimeError, " for "+theInfo+" returns false" + raise RuntimeError(" 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, " for "+theInfo+" returns None object" + raise RuntimeError(" 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) diff --git a/src/KERNEL_PY/salome_test.py b/src/KERNEL_PY/salome_test.py index e0bdd983f..08070cb21 100755 --- a/src/KERNEL_PY/salome_test.py +++ b/src/KERNEL_PY/salome_test.py @@ -21,10 +21,10 @@ # 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 diff --git a/src/KERNEL_PY/salome_version.py b/src/KERNEL_PY/salome_version.py index a17424a15..1642ed9a7 100644 --- a/src/KERNEL_PY/salome_version.py +++ b/src/KERNEL_PY/salome_version.py @@ -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 ) diff --git a/src/KernelHelpers/Test/TestKernelHelpers.py b/src/KernelHelpers/Test/TestKernelHelpers.py index 23855be65..c94b5d55c 100644 --- a/src/KernelHelpers/Test/TestKernelHelpers.py +++ b/src/KernelHelpers/Test/TestKernelHelpers.py @@ -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 diff --git a/src/Launcher/Test/test_launcher.py b/src/Launcher/Test/test_launcher.py index 53fe67af5..2b9ee1583 100755 --- a/src/Launcher/Test/test_launcher.py +++ b/src/Launcher/Test/test_launcher.py @@ -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") diff --git a/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py b/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py index 68d582703..6d52cebce 100644 --- a/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py +++ b/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py @@ -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 diff --git a/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py b/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py index 6690b5193..303d2cc1b 100644 --- a/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py +++ b/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py @@ -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 diff --git a/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py b/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py index 36f2a570c..073af7047 100644 --- a/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py +++ b/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py @@ -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 diff --git a/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py b/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py index 878797b5b..2f7d481cd 100644 --- a/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py +++ b/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py @@ -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') diff --git a/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i b/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i index 2f80c10c1..ecfef6ab9 100644 --- a/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i +++ b/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i @@ -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); %} diff --git a/src/Logger/SALOME_Trace.py b/src/Logger/SALOME_Trace.py index f2cc791a3..faf4c3421 100644 --- a/src/Logger/SALOME_Trace.py +++ b/src/Logger/SALOME_Trace.py @@ -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) diff --git a/src/Logger/Test/TestKiller.py b/src/Logger/Test/TestKiller.py index a05bfd39a..7a41210ac 100644 --- a/src/Logger/Test/TestKiller.py +++ b/src/Logger/Test/TestKiller.py @@ -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 diff --git a/src/MPIContainer/MPIContainer_i.cxx b/src/MPIContainer/MPIContainer_i.cxx index ddda604a4..86fc22b16 100644 --- a/src/MPIContainer/MPIContainer_i.cxx +++ b/src/MPIContainer/MPIContainer_i.cxx @@ -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; diff --git a/src/ModuleCatalog/TestModuleCatalog.py b/src/ModuleCatalog/TestModuleCatalog.py index 9e89c6a6d..de3c69a6a 100755 --- a/src/ModuleCatalog/TestModuleCatalog.py +++ b/src/ModuleCatalog/TestModuleCatalog.py @@ -24,63 +24,63 @@ 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 diff --git a/src/ModuleGenerator/IDLparser.py b/src/ModuleGenerator/IDLparser.py index 0f2ab825d..bc10283c5 100644 --- a/src/ModuleGenerator/IDLparser.py +++ b/src/ModuleGenerator/IDLparser.py @@ -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]* -Wbcatalog=[,icon=][,version=][,author=][,name=][,username=][,multistudy=][,impltype=] " - print + print() + print("Usage : omniidl -bIDLparser [-I]* -Wbcatalog=[,icon=][,version=][,author=][,name=][,username=][,multistudy=][,impltype=] ") + print() diff --git a/src/NamingService/SALOME_NamingServicePy.py b/src/NamingService/SALOME_NamingServicePy.py index 4233797e6..7ca7f90fd 100644 --- a/src/NamingService/SALOME_NamingServicePy.py +++ b/src/NamingService/SALOME_NamingServicePy.py @@ -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) diff --git a/src/NamingService/Test/TestNamingService.py b/src/NamingService/Test/TestNamingService.py index 51fe25b2d..e8c2a8203 100644 --- a/src/NamingService/Test/TestNamingService.py +++ b/src/NamingService/Test/TestNamingService.py @@ -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 diff --git a/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx b/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx index 25267d785..14ae2c232 100644 --- a/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx +++ b/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx @@ -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; diff --git a/src/ParallelContainer/SALOME_ParallelContainer_i.cxx b/src/ParallelContainer/SALOME_ParallelContainer_i.cxx index 14a612934..313de0686 100644 --- a/src/ParallelContainer/SALOME_ParallelContainer_i.cxx +++ b/src/ParallelContainer/SALOME_ParallelContainer_i.cxx @@ -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; diff --git a/src/SALOMEDS/Test/TestSALOMEDS.py b/src/SALOMEDS/Test/TestSALOMEDS.py index 863a12eab..2551d4bdb 100644 --- a/src/SALOMEDS/Test/TestSALOMEDS.py +++ b/src/SALOMEDS/Test/TestSALOMEDS.py @@ -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 diff --git a/src/SALOMEDSImpl/Test/TestSALOMEDSImpl.py b/src/SALOMEDSImpl/Test/TestSALOMEDSImpl.py index df3697b5b..0b0daf2bd 100644 --- a/src/SALOMEDSImpl/Test/TestSALOMEDSImpl.py +++ b/src/SALOMEDSImpl/Test/TestSALOMEDSImpl.py @@ -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 diff --git a/src/SALOMELocalTrace/Test/TestSALOMELocalTrace.py b/src/SALOMELocalTrace/Test/TestSALOMELocalTrace.py index 436af9931..3c621ee5b 100644 --- a/src/SALOMELocalTrace/Test/TestSALOMELocalTrace.py +++ b/src/SALOMELocalTrace/Test/TestSALOMELocalTrace.py @@ -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 diff --git a/src/SALOMESDS/SALOMEGlobalVarHelper.py b/src/SALOMESDS/SALOMEGlobalVarHelper.py index d3bc10619..9d8a641fc 100644 --- a/src/SALOMESDS/SALOMEGlobalVarHelper.py +++ b/src/SALOMESDS/SALOMEGlobalVarHelper.py @@ -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) diff --git a/src/SALOMESDS/SALOMESDS_DataScopeServer.cxx b/src/SALOMESDS/SALOMESDS_DataScopeServer.cxx index 92dae7794..742898101 100644 --- a/src/SALOMESDS/SALOMESDS_DataScopeServer.cxx +++ b/src/SALOMESDS/SALOMESDS_DataScopeServer.cxx @@ -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]) !"; diff --git a/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdExtServer.cxx b/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdExtServer.cxx index 7a5cd58b7..db1b19fb7 100644 --- a/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdExtServer.cxx +++ b/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdExtServer.cxx @@ -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); diff --git a/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdWrServer.cxx b/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdWrServer.cxx index cf780a09d..8ffe04848 100644 --- a/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdWrServer.cxx +++ b/src/SALOMESDS/SALOMESDS_PickelizedPyObjRdWrServer.cxx @@ -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 << " )"; diff --git a/src/SALOMESDS/SALOMESDS_PickelizedPyObjServer.cxx b/src/SALOMESDS/SALOMESDS_PickelizedPyObjServer.cxx index 7de5f2c2b..8e219d27f 100644 --- a/src/SALOMESDS/SALOMESDS_PickelizedPyObjServer.cxx +++ b/src/SALOMESDS/SALOMESDS_PickelizedPyObjServer.cxx @@ -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& 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(ret.c_str())); for(std::size_t i=0;i @@ -40,7 +40,7 @@ class TestEnvironment: = 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 */ -- 2.39.2