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()
else:
getNSparams()
# keep print, stdout used in shell
- print my_host, my_port
+ print(my_host, my_port)
pass
pass
#
# 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)
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
config = {}
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)
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))
port = port + 1
logger.debug("found free port: %s"%str(port))
# write config
logger.debug("write config: %s"%str(config))
try:
- with open(config_file, 'w') as f:
+ with open(config_file, 'wb') as f:
pickle.dump(config, f)
except IOError:
pass
config = {}
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
# write config
logger.debug("write config: %s"%str(config))
try:
- with open(config_file, 'w') as f:
+ with open(config_file, 'wb') as f:
pickle.dump(config, f)
except IOError:
pass
config = {}
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
"""
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):
# 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
# 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
pass
# kill processes
for process_id in process_ids:
- #print process_id
- for pid, cmd in process_id.items():
+ # print(process_id)
+ 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
pass
if __name__ == "__main__":
- if verbose(): print sys.argv
+ if verbose(): print(sys.argv)
addToKillList(sys.argv[1], sys.argv[2])
pass
#! /usr/bin/env python
-# -*- 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,
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"] = []
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
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
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
# 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
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)
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)
#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)
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)
"""
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
applipath = relpath(os.path.realpath(os.path.dirname(__file__)),os.path.realpath(os.getenv('HOME')))
else:
applipath = get_appli_path()
- print applipath
+ print(applipath)
#
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
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__':
-#! /usr/bin/env python
+#! /usr/bin/env python3
# Copyright (C) 2013-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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
sys.stdout.write(out)
if err:
sys.stderr.write(err)
- #print 'Thank you for using SALOME!'
+ # 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)
appliPath = __detectAppliPath(launcherPath, launcherFile)
if appliPath is None:
- print "ERROR: Unable to find application folder"
+ print("ERROR: Unable to find application folder")
sys.exit(1)
appliPath = os.path.relpath(appliPath, homePath)
try:
from salomeContextUtils import setOmniOrbUserPath
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
# End of preliminary work
#
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()
#
# 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
#
# 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.")
sys.exit(1)
_, ext = os.path.splitext(args[0])
if ext == ".py":
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
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()
pass
if sys.platform == 'win32':
timer.cancel()
- print "Exit test with status code:", res
+ print("Exit test with status code:", res)
sys.exit(res)
#
# 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.")
sys.exit(1)
_, ext = os.path.splitext(args[0])
test_and_args = args
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
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()
pass
if sys.platform == 'win32':
timer.cancel()
-# print "Exit test with status code:", res
+# print("Exit test with status code:", res)
# sys.exit(res)
#
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)
#
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()
#
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
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"],))
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()
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()
if __name__ == "__main__":
if not os.path.isfile("hello.py"):
with open("hello.py", "w") as f:
- f.write("print 'Hello!'")
+ f.write("print('Hello!')")
unittest.main()
#
port = getPort(prefered)
else:
port = getPort()
- print "obtained port = %s"%port
+ print("obtained port = %s"%port)
obtained_ports.put(port)
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 = [
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()
p.join()
# Release port
- print "release port 2812"
+ print("release port 2812")
p = multiprocessing.Process(target=releasePort, args=(2812,))
p.start()
p.join()
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,))
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")
#
#
# make hello.py
echo "
#!/usr/bin/env python
-print 'Hello\!'
+print('Hello\!')
" > ${BASE_DIR}/hello.py
# Build output folders
import os
import sys
import imp
-from cStringIO import StringIO
+from io import StringIO
import logging
logger = logging.getLogger("TestLauncherLogger")
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
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()
#
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)
#
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)
#
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()
#
# 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()
#
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
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")
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
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=[]
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)
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)
try:
from salomeContextUtils import setOmniOrbUserPath
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
killAllPorts()
pass
# \endcode
#
-import os, sys, pickle, signal, commands,glob
+import os, sys, pickle, signal, subprocess,glob
import subprocess
import shlex
from salome_utils import verbose
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")
# 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)
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
log_msg += " ... not found\n"
if verbose():
- print log_msg
+ print(log_msg)
return filedict
#
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
if __name__ == "__main__":
if len(sys.argv) < 2:
- print "Usage: "
- print " %s <port>" % os.path.basename(sys.argv[0])
- print
- print "Kills SALOME session running on specified <port>."
+ print("Usage: ")
+ print(" %s <port>" % os.path.basename(sys.argv[0]))
+ print()
+ print("Kills SALOME session running on specified <port>.")
sys.exit(1)
pass
if sys.argv[1] == "--spy":
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)
import types
from salome_utils import verbose, getPortNumber, getHomeDir
+from six import string_types
# names of tags in XML configuration file
doc_tag = "document"
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
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)
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"):
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
section_name = attrs.getValue( nam_att )
if section_name in [lanch_nam, lang_nam]:
self.section = section_name # launch section
- elif self.opts.has_key( modules_nam ) and \
+ elif modules_nam in self.opts and \
section_name in self.opts[ modules_nam ]:
self.section = section_name # <module> section
else:
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
# 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
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 ) ) ) )
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 ) ) ) )
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:
# check KERNEL_ROOT_DIR
kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
if kernel_root_dir is None:
- print """
+ print("""
For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
KERNEL_ROOT_DIR is mandatory.
- """
+ """)
sys.exit(1)
############################
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
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
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
args['user_config'] = user_config
- #print "User Configuration file: ", args['user_config']
+ # print("User Configuration file: ", args['user_config'])
# 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]:
# 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 ),
elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ):
dirs.append( d2 )
else:
- #print "* '"+m+"' should be deleted from ",args[modules_nam]
+ # print("* '"+m+"' should be deleted from ",args[modules_nam])
pass
# Test
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
# return arguments
os.environ[config_var] = os.pathsep.join(dirs)
- #print "Args: ", args
+ # print("Args: ", args)
return args
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();
else:
hname = socket.gethostname();
- #print "hname=",hname
+ # print("hname=",hname)
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]
try:
os.mkdir(upath)
except:
- #print "Can't create " + upath
+ # print("Can't create " + upath)
pass
#os.system("touch " + upath + "/dummy")
#os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
#aSedCommand="s/.*NameService=corbaname::" + hname + ":\([[:digit:]]*\)/\1/"
- #print "sed command = ", aSedCommand
+ # print("sed command = ", aSedCommand)
#aPort = commands.getoutput("sed -e\"" + aSedCommand + "\"" + os.environ["OMNIORB_CONFIG"])
- #print "port=", aPort
+ # print("port=", aPort)
if sys.platform == "win32":
- #print "start omniNames -start " + aPort + " -logdir " + upath
+ # print("start omniNames -start " + aPort + " -logdir " + upath)
self.CMD = ['omniNames', '-start' , aPort , '-nohostname', '-logdir' , os.path.realpath(upath), '-errlog', os.path.realpath(os.path.join(upath,'omniNameErrors.log'))]
#os.system("start omniNames -start " + aPort + " -logdir " + upath)
else:
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):
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
if test:
NamingServer(args).run()
pass
- print "Searching Naming Service ",
+ print("Searching Naming Service ", end=' ')
ncount=0
delta=0.1
while(ncount < 100):
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)
# --------------------------------------------------------------------------
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 = []
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
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('+')
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":
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('+')
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
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
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('+')
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
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import ConfigParser
+import configparser
import os
import logging
import re
#
# :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
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()
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)
# 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:
# 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)
#
# 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)
#
from optparse import OptionParser
import os
import sys
-import user
import pickle
# Use to display newlines (\n) in epilog
The -c option can be used to specify the command to execute in the interpreter.
A script can also be used.
For example:
- salome connect -p 2810 -c 'print "Hello"'
+ salome connect -p 2810 -c 'print("Hello")'
salome connect -p 2810 hello.py
"""
parser = MyParser(usage=usage, epilog=epilog)
)
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)
#
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
#
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
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"):
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()
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!")
#
try:
killMyPort(my_port)
except:
- print "problem in killLocalPort()"
+ print("problem in killLocalPort()")
pass
pass
try:
killMyPort(my_port)
except:
- print "problem in LocalPortKill(), killMyPort(%s)"%port
+ print("problem in LocalPortKill(), killMyPort(%s)"%port)
pass
pass
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
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)
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
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
# ---
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
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']
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
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:
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
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"]:
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
#
"""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'])
#
# and wait until it is registered in naming service
#
- #print "ARGS = ",args
+ # 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":
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']:
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()
except:
import traceback
traceback.print_exc()
- print
- print
- print "--- Error during Salome launch ---"
+ print()
+ print()
+ print("--- Error during Salome launch ---")
- #print process_id
+ # print(process_id)
from addToKillList import addToKillList
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
runSalome, with --killall option, starts with killing
the processes resulting from the previous execution.
- """%filedict
+ """%filedict)
#
# Print Naming Service directory list
if clt != None:
if verbose():
- print
- print " --- registered objects tree in Naming Service ---"
+ print()
+ print(" --- registered objects tree in Naming Service ---")
clt.showNS()
pass
# 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)
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]
# -----------------------------------------------------------------------------
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
#
def runSalome():
- import user
clt,args = main()
# --
test = args['gui'] and args['session_gui']
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
# 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)
# 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
# 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
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
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)
return []
if args[0] in ["-h", "--help"]:
- print usage + epilog
+ print(usage + epilog)
sys.exit(0)
return args
import os
import sys
import logging
-import ConfigParser
+import configparser
from parseConfigFile import parseConfigFile
any blank characters.
'''
- print msg
+ print(msg)
#
"""
#
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
#
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
#
'car' : '_getCar',
}
- if not command in availableCommands.keys():
+ if command not in availableCommands:
command = "start"
options = args
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)
return returncode
- except StandardError:
+ except SalomeContextException as e:
+ self.getLogger().error(e)
+ return 1
+ except Exception:
self.getLogger().error("Unexpected error:")
import traceback
traceback.print_exc()
return 1
- except SalomeContextException, e:
- self.getLogger().error(e)
- return 1
#
def __setContextFromConfigFile(self, filename, reserved=None):
reserved = []
try:
unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
- except SalomeContextException, e:
+ except SalomeContextException as e:
msg = "%s"%e
self.getLogger().error(msg)
return 1
# 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"]:
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)
args = []
ports = args
if not ports:
- print "Port number(s) not provided to command: salome kill <port(s)>"
+ print("Port number(s) not provided to command: salome kill <port(s)>")
return
from multiprocessing import Process
#
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 = {}
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):
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:
this_ports = ports['this']
other_ports = ports['other']
if this_ports or other_ports:
- print "SALOME instances are running on the following ports:"
+ print("SALOME instances are running on the following ports:")
if this_ports:
- print " This application:", this_ports
+ print(" This application:", this_ports)
else:
- print " No SALOME instances of this application"
+ print(" No SALOME instances of this application")
if other_ports:
- print " Other applications:", other_ports
+ print(" Other applications:", other_ports)
else:
- print " No SALOME instances of other applications"
+ print(" No SALOME instances of other applications")
else:
- print "No SALOME instances are running"
+ print("No SALOME instances are running")
if "-s" in args or "--softwares" in args:
if "-s" in args:
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"])
#
modules = args
if not modules:
- print "Module(s) not provided to command: salome doc <module(s)>"
+ print("Module(s) not provided to command: salome doc <module(s)>")
return
appliPath = os.getenv("ABSOLUTE_APPLI_PATH")
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("")
#
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("")
#
# Add the following two methods since logger is not pickable
if __name__ == "__main__":
if len(sys.argv) == 3:
- context = pickle.loads(sys.argv[1])
- args = pickle.loads(sys.argv[2])
+ context = pickle.loads(sys.argv[1].encode())
+ args = pickle.loads(sys.argv[2].encode())
context._startSalome(args)
else:
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:
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
If <arg> does not represent a boolean, an exception is raised.
"""
import types
- if type( arg ) == types.BooleanType :
+ if type( arg ) == bool :
return arg
- elif type( arg ) == types.StringType :
+ elif type( arg ) == bytes :
v = str( arg ).lower()
if v in [ "yes", "y", "true" ]: return True
elif v in [ "no", "n", "false" ]: return False
### 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
# ---
-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.
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
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)
ret = 1
pass
pass
- except OSError, e:
+ except OSError as e:
# errno.ESRCH == 3 is 'No such process'
if e.errno == 3:
ret = 0
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'],
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:
+ os.getenv("LD_LIBRARY_PATH")]
myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
command = myargs + self.CMD
- #print "command = ", command
+ # print("command = ", command)
if sys.platform == "win32":
import subprocess
pid = subprocess.Popen(command).pid
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)
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)
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):
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)]
#*** Test additional option
#*** args = launchConfigureParser.get_env([o_j])
- #*** if args.has_key("join"): print args["join"]
+ #*** if args.has_key("join"): print(args["join"])
# Check variables <module>_ROOT_DIR
# 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"] :
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
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]
"LD_LIBRARY_PATH")
add_path(os.path.join(module_root_dir,"bin",salome_subdir),
"PATH")
- if os.path.exists(module_root_dir + "/examples") :
- add_path(os.path.join(module_root_dir,"examples"),
+ if os.path.exists(os.path.join(module_root_dir, "examples")):
+ add_path(os.path.join(module_root_dir, "examples"),
"PYTHONPATH")
pass
add_path(os.path.join(module_root_dir,"bin",salome_subdir),
# 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]
if args['logger']:
os.environ["SALOME_trace"]="with_logger"
-# -*- 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,
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-
"""Create a virtual Salome installation
Based on a script created by Ian Bicking.
install module KERNEL in the current directory
"""
-import sys, os, optparse, shutil,glob,fnmatch
+import sys, os, optparse, shutil, glob, fnmatch
+
+
py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
verbose=0
"""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
"""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
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
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
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')
pass
else:
if verbose:
- print module_bin_dir, " doesn't exist"
+ print(module_bin_dir, " doesn't exist")
pass
#directory bin/salome/test : create it and link content
if os.path.exists(module_test_dir):
# link <appli_path>/bin/salome/test/<module> to <module_path>/bin/salome/test
- print "link %s --> %s"%(os.path.join(test_dir, options.module_name), module_test_dir)
+ print("link %s --> %s"%(os.path.join(test_dir, options.module_name), module_test_dir))
symlink(module_test_dir, os.path.join(test_dir, options.module_name))
# register module for testing in CTestTestfile.cmake
with open(os.path.join(test_dir, "CTestTestfile.cmake"), "ab") as f:
- f.write("SUBDIRS(%s)\n"%options.module_name)
+ aStr = "SUBDIRS(%s)\n"%options.module_name
+ f.write(aStr.encode())
else:
if verbose:
- print module_test_dir, " doesn't exist"
+ print(module_test_dir, " doesn't exist")
pass
#directory idl/salome : create it and link content
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):
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
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")
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
#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
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
#directory bin/salome/test : create it and link content
if os.path.exists(extra_test_dir):
# link <appli_path>/bin/salome/test/<extra_test> to <extra_test_path>/bin/salome/test
- print "link %s --> %s"%(os.path.join(test_dir, options.extra_test_name), extra_test_dir)
+ print("link %s --> %s"%(os.path.join(test_dir, options.extra_test_name), extra_test_dir))
symlink(extra_test_dir, os.path.join(test_dir, options.extra_test_name))
# register extra_test for testing in CTestTestfile.cmake
with open(os.path.join(test_dir, "CTestTestfile.cmake"), "ab") as f:
- f.write("SUBDIRS(%s)\n"%options.extra_test_name)
+ aStr = "SUBDIRS(%s)\n" % options.extra_test_name
+ f.write(aStr.encode())
else:
if verbose:
- print extra_test_dir, " doesn't exist"
+ print(extra_test_dir, " doesn't exist")
pass
# -----------------------------------------------------------------------------
--- /dev/null
+# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
+#
+# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+"""Create a virtual Salome installation
+
+Based on a script created by Ian Bicking.
+
+Typical use::
+
+ python virtual_salome.py -v --prefix="." --module=/local/chris/SALOME2/RELEASES/Install/KERNEL_V3_1_0b1
+
+install module KERNEL in the current directory
+"""
+
+import sys, os, optparse, shutil, glob, fnmatch
+
+
+py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
+
+verbose=0
+
+# -----------------------------------------------------------------------------
+
+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)
+ os.makedirs(path)
+ else:
+ if verbose:
+ print('Directory %s already exists' % path)
+ pass
+ pass
+
+# -----------------------------------------------------------------------------
+
+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)
+ return
+ if verbose:
+ print('Creating symlink %s' % dest)
+ pass
+ os.symlink(src, dest)
+ else:
+ if verbose:
+ print('Symlink %s already exists' % dest)
+ pass
+ pass
+
+# -----------------------------------------------------------------------------
+
+def rmtree(dir):
+ """Remove (recursive) a directory if it exists"""
+ if os.path.exists(dir):
+ print('Deleting tree %s' % dir)
+ shutil.rmtree(dir)
+ else:
+ if verbose:
+ print('Do not need to delete %s; already gone' % dir)
+ pass
+ pass
+ pass
+
+# -----------------------------------------------------------------------------
+
+__lib__dir__ = None
+def get_lib_dir():
+ global __lib__dir__
+ if __lib__dir__: return __lib__dir__
+ import platform
+ __lib__dir__ = "lib"
+ return __lib__dir__
+
+# -----------------------------------------------------------------------------
+
+def link_module(options):
+ global verbose
+
+ if not options.module_path:
+ 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)
+ return
+
+ verbose = options.verbose
+
+ home_dir = os.path.expanduser(options.prefix)
+ #try to find python version of salome application and put it in versio
+ pys=[os.path.split(s)[1] for s in glob.glob(os.path.join(home_dir,get_lib_dir(),"python*.*"))]
+ if not pys :
+ versio=None
+ else:
+ versio=pys[0]
+
+ pys=[os.path.split(s)[1] for s in glob.glob(os.path.join(module_dir,get_lib_dir(),"python*.*"))]
+ #check if the module has a python version compatible with application version
+ if not pys :
+ pyversio=versio or py_version
+ elif versio is None:
+ pyversio=pys[0]
+ elif versio in pys:
+ pyversio=versio
+ else:
+ #incompatible python versions
+ 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')
+ module_test_dir=os.path.join(module_dir,'bin','salome', 'test')
+ module_idl_dir=os.path.join(module_dir,'idl','salome')
+ module_lib_dir=os.path.join(module_dir,get_lib_dir(),'salome')
+ module_pvlib_dir=os.path.join(module_dir,get_lib_dir(),'paraview')
+ module_lib_py_dir=os.path.join(module_dir,get_lib_dir(),pyversio,'site-packages','salome')
+ module_lib_py_shared_dir=os.path.join(module_dir,get_lib_dir(),pyversio,
+ 'site-packages','salome')
+ module_share_dir=os.path.join(module_dir,'share','salome')
+ module_doc_gui_dir=os.path.join(module_dir,'doc','salome','gui')
+ module_doc_tui_dir=os.path.join(module_dir,'doc','salome','tui')
+ module_doc_dir=os.path.join(module_dir,'doc','salome')
+ module_sharedoc_dir=os.path.join(module_dir,'share','doc','salome')
+ module_sharedoc_gui_dir=os.path.join(module_dir,'share','doc','salome','gui')
+ module_sharedoc_tui_dir=os.path.join(module_dir,'share','doc','salome','tui')
+ module_sharedoc_examples=os.path.join(module_dir,'share','doc','salome','examples')
+ module_sharedoc_dev=os.path.join(module_dir,'share','doc','salome','dev')
+
+ bin_dir=os.path.join(home_dir,'bin','salome')
+ test_dir=os.path.join(home_dir,'bin','salome', 'test')
+ idl_dir=os.path.join(home_dir,'idl','salome')
+ lib_dir=os.path.join(home_dir,'lib','salome')
+ pvlib_dir=os.path.join(home_dir,'lib','paraview')
+ lib_py_dir=os.path.join(home_dir,'lib',pyversio,'site-packages','salome')
+ lib_py_shared_dir=os.path.join(home_dir,'lib',pyversio,
+ 'site-packages','salome')
+ share_dir=os.path.join(home_dir,'share','salome')
+ doc_gui_dir=os.path.join(home_dir,'doc','salome','gui')
+ doc_tui_dir=os.path.join(home_dir,'doc','salome','tui')
+ doc_dir=os.path.join(home_dir,'doc','salome')
+ sharedoc_dir=os.path.join(home_dir,'share','doc','salome')
+ sharedoc_gui_dir=os.path.join(home_dir,'share','doc','salome','gui')
+ sharedoc_tui_dir=os.path.join(home_dir,'share','doc','salome','tui')
+ sharedoc_examples_dir=os.path.join(home_dir,'share','doc','salome','examples')
+ sharedoc_dev_dir=os.path.join(home_dir,'share','doc','salome','dev')
+
+ if options.clear:
+ rmtree(bin_dir)
+ rmtree(test_dir)
+ rmtree(idl_dir)
+ rmtree(lib_dir)
+ rmtree(lib_py_dir)
+ rmtree(share_dir)
+ rmtree(doc_dir)
+ rmtree(sharedoc_dir)
+ pass
+
+ #directory bin/salome : create it and link content
+ if os.path.exists(module_bin_dir):
+ mkdir(bin_dir)
+ mkdir(test_dir)
+ for fn in os.listdir(module_bin_dir):
+ if fn != "test":
+ symlink(os.path.join(module_bin_dir, fn), os.path.join(bin_dir, fn))
+ pass
+ pass
+ else:
+ if verbose:
+ print(module_bin_dir, " doesn't exist")
+ pass
+
+ #directory bin/salome/test : create it and link content
+ if os.path.exists(module_test_dir):
+ # link <appli_path>/bin/salome/test/<module> to <module_path>/bin/salome/test
+ print("link %s --> %s"%(os.path.join(test_dir, options.module_name), module_test_dir))
+ 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:
+ aStr = "SUBDIRS(%s)\n"%options.module_name
+ f.write(aStr.encode())
+ else:
+ if verbose:
+ print(module_test_dir, " doesn't exist")
+ pass
+
+ #directory idl/salome : create it and link content
+ if os.path.exists(module_idl_dir):
+ mkdir(idl_dir)
+ for fn in os.listdir(module_idl_dir):
+ symlink(os.path.join(module_idl_dir, fn), os.path.join(idl_dir, fn))
+ else:
+ if verbose:
+ print(module_idl_dir, " doesn't exist")
+
+ #directory lib/salome : create it and link content
+ if os.path.exists(module_lib_dir):
+ mkdir(lib_dir)
+ for fn in os.listdir(module_lib_dir):
+ symlink(os.path.join(module_lib_dir, fn), os.path.join(lib_dir, fn))
+ pass
+ pass
+ else:
+ if verbose:
+ print(module_lib_dir, " doesn't exist")
+ pass
+
+ #directory lib/paraview : create it and link content
+ if os.path.exists(module_pvlib_dir):
+ mkdir(pvlib_dir)
+ for fn in os.listdir(module_pvlib_dir):
+ symlink(os.path.join(module_pvlib_dir, fn), os.path.join(pvlib_dir, fn))
+ pass
+ pass
+ else:
+ if verbose:
+ 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)
+ else:
+ # Specific action for the package salome
+ module_lib_pypkg_dir=os.path.join(module_lib_py_dir,"salome")
+ lib_pypkg_dir=os.path.join(lib_py_dir,"salome")
+ mkdir(lib_pypkg_dir)
+ mkdir(lib_py_shared_dir)
+ for fn in os.listdir(module_lib_py_dir):
+ if fn == "salome": continue
+ symlink(os.path.join(module_lib_py_dir, fn), os.path.join(lib_py_dir, fn))
+ pass
+ if os.path.exists(module_lib_py_shared_dir):
+ for fn in os.listdir(module_lib_py_shared_dir):
+ symlink(os.path.join(module_lib_py_shared_dir, fn), os.path.join(lib_py_shared_dir, fn))
+ pass
+ pass
+ if os.path.exists(module_lib_pypkg_dir):
+ for fn in os.listdir(module_lib_pypkg_dir):
+ symlink(os.path.join(module_lib_pypkg_dir, fn), os.path.join(lib_pypkg_dir, fn))
+ pass
+ pass
+ else:
+ if verbose:
+ print(module_lib_py_shared_dir, " doesn't exist")
+ pass
+
+ #directory share/doc/salome (KERNEL doc) : create it and link content
+ if os.path.exists(module_sharedoc_dir):
+ mkdir(sharedoc_dir)
+ for fn in os.listdir(module_sharedoc_dir):
+ if fn == 'gui':continue
+ if fn == 'tui':continue
+ if fn == 'examples':continue
+ if fn == 'dev':continue
+ symlink(os.path.join(module_sharedoc_dir, fn), os.path.join(sharedoc_dir, fn))
+ pass
+ pass
+
+ #directory share/doc/salome/gui : create it and link content
+ if os.path.exists(module_sharedoc_gui_dir):
+ mkdir(sharedoc_gui_dir)
+ for fn in os.listdir(module_sharedoc_gui_dir):
+ symlink(os.path.join(module_sharedoc_gui_dir, fn), os.path.join(sharedoc_gui_dir, fn))
+ pass
+ pass
+
+ #directory share/doc/salome/tui : create it and link content
+ if os.path.exists(module_sharedoc_tui_dir):
+ mkdir(sharedoc_tui_dir)
+ for fn in os.listdir(module_sharedoc_tui_dir):
+ symlink(os.path.join(module_sharedoc_tui_dir, fn), os.path.join(sharedoc_tui_dir, fn))
+ pass
+ pass
+
+ #directory share/doc/salome/examples : create it and link content
+ if os.path.exists(module_sharedoc_examples):
+ mkdir(sharedoc_examples_dir)
+ for fn in os.listdir(module_sharedoc_examples):
+ symlink(os.path.join(module_sharedoc_examples, fn), os.path.join(sharedoc_examples_dir, fn))
+ pass
+ pass
+
+ #directory share/doc/salome/dev : create it and link content
+ if os.path.exists(module_sharedoc_dev):
+ mkdir(sharedoc_dev_dir)
+ for fn in os.listdir(module_sharedoc_dev):
+ symlink(os.path.join(module_sharedoc_dev, fn), os.path.join(sharedoc_dev_dir, fn))
+ pass
+ pass
+
+ #directory share/salome : create it and link content
+ if os.path.exists(module_share_dir):
+ mkdir(share_dir)
+ for fn in os.listdir(module_share_dir):
+ if fn in ["resources","plugins"] :
+ # Create the directory and then link the content
+ mkdir(os.path.join(share_dir,fn))
+ for ffn in os.listdir(os.path.join(module_share_dir,fn)):
+ symlink(os.path.join(module_share_dir, fn, ffn), os.path.join(share_dir,fn, ffn))
+ else:
+ #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)
+ pass
+
+ #html files in doc/salome directory
+ if os.path.exists(module_doc_dir):
+ mkdir(doc_dir)
+ for fn in os.listdir(module_doc_dir):
+ if fn == 'gui':continue
+ if fn == 'tui':continue
+ symlink(os.path.join(module_doc_dir, fn), os.path.join(doc_dir, fn))
+ pass
+ pass
+
+ #directory doc/salome/gui : create it and link content
+ if os.path.exists(module_doc_gui_dir):
+ mkdir(doc_gui_dir)
+ for fn in os.listdir(module_doc_gui_dir):
+ symlink(os.path.join(module_doc_gui_dir, fn), os.path.join(doc_gui_dir, fn))
+ pass
+ pass
+
+ #directory doc/salome/tui : create it and link content
+ if os.path.exists(module_doc_tui_dir):
+ mkdir(doc_tui_dir)
+ for fn in os.listdir(module_doc_tui_dir):
+ symlink(os.path.join(module_doc_tui_dir, fn), os.path.join(doc_tui_dir, fn))
+ pass
+ pass
+
+def link_extra_test(options):
+ global verbose
+
+ if not options.extra_test_path:
+ 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)
+ return
+
+ verbose = options.verbose
+
+ home_dir = os.path.expanduser(options.prefix)
+ test_dir = os.path.join(home_dir,'bin','salome', 'test')
+
+ if options.clear:
+ rmtree(test_dir)
+ pass
+
+ #directory bin/salome/test : create it and link content
+ if os.path.exists(extra_test_dir):
+ # link <appli_path>/bin/salome/test/<extra_test> to <extra_test_path>/bin/salome/test
+ print("link %s --> %s"%(os.path.join(test_dir, options.extra_test_name), extra_test_dir))
+ 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:
+<<<<<<< HEAD
+ aStr ="SUBDIRS(%s)\n"%options.extra_test_name
+=======
+ aStr = "SUBDIRS(%s)\n" % options.extra_test_name
+>>>>>>> 6c4f7677e815be0b7562380fc85bb0ece08800cb
+ f.write(aStr.encode())
+ else:
+ if verbose:
+ print(extra_test_dir, " doesn't exist")
+ pass
+
+# -----------------------------------------------------------------------------
+
+def main():
+ usage="""usage: %prog [options]
+Typical use is:
+ python virtual_salome.py -v --prefix="." --module=/local/chris/SALOME2/RELEASES/Install/KERNEL_V3_1_0b1
+"""
+ parser = optparse.OptionParser(usage=usage)
+
+ parser.add_option('-v', '--verbose', action='count', dest='verbose',
+ default=0, help="Increase verbosity")
+
+ parser.add_option('--prefix', dest="prefix", default='.',
+ help="The base directory to install to (default .)")
+
+ parser.add_option('--module', dest="module",
+ help="The module directory to install in (mandatory)")
+
+ parser.add_option('--clear', dest='clear', action='store_true',
+ help="Clear out the install and start from scratch")
+
+ options, args = parser.parse_args()
+ link_module(options)
+ pass
+
+# -----------------------------------------------------------------------------
+
+if __name__ == '__main__':
+ main()
+ pass
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)
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()
#file = "/tmp/ggg.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
openedStudy=batchmode_geompy.myStudyManager.Open(file)
c = A.TextColor();
if c.R != 234 or c.G != 345 or c.B != 231:
- print "Error: wrong value of AttributeTextColor"
+ print("Error: wrong value of AttributeTextColor")
# save / restore study
#============================================================
c = A.TextColor();
if c.R != 234 or c.G != 345 or c.B != 231:
- print "Error: wrong value of AttributeTextColor"
+ print("Error: wrong value of AttributeTextColor")
c = A.TextHighlightColor();
if c.R != 256 or c.G != 256 or c.B != 256:
- print "Error: wrong value of AttributeTextHighlightColor"
+ print("Error: wrong value of AttributeTextHighlightColor")
# save / restore study
#============================================================
res, A = father.FindAttribute("AttributeTextHighlightColor")
-print res, A
+print(res, A)
if res == 0 or A == None:
raise RuntimeError, "Error: not found AttributeTextHighlightColor"
c = A.TextHighlightColor();
if c.R != 256 or c.G != 256 or c.B != 256:
- print "Error: wrong value of AttributeTextTextHighlightColor"
+ print("Error: wrong value of AttributeTextTextHighlightColor")
aPixmap.SetPixMap( "ICON_OBJBROWSER_Geometry" );
if aPixmap.GetPixMap() != "ICON_OBJBROWSER_Geometry":
- print "Error: wrong value of AttributePixMap"
+ print("Error: wrong value of AttributePixMap")
# save / restore study
raise RuntimeError, "Can't create AttributePixMap attribute"
if A.GetPixMap() != "ICON_OBJBROWSER_Geometry":
- print "Error: wrong value of AttributePixMap"
+ print("Error: wrong value of AttributePixMap")
A.SetValue(763242882)
if A.Value() != 763242882:
- print "Error: wrong value of AttributeLocalID"
+ print("Error: wrong value of AttributeLocalID")
# save / restore study
#=================================
A = A._narrow(SALOMEDS.AttributeLocalID)
if A.Value() != 763242882:
- print "Error: wrong value of AttributeLocalID"
+ print("Error: wrong value of AttributeLocalID")
A.Add(500)
A.Add(400)
A.Add(700)
-print "First transaction goes on : HasOpenCommand() = ", batchmode_geompy.myBuilder.HasOpenCommand()
+print("First transaction goes on : HasOpenCommand() = ", batchmode_geompy.myBuilder.HasOpenCommand())
batchmode_geompy.myBuilder.CommitCommand() #--------------
# 2nd transaction ------------------------------------------
raise RuntimeError, "GetAvailableUndos() = 0 but must not !"
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 500:
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger"
if A is None:
raise RuntimeError, "After first 'undo' can't find AttributeSequenceOfInteger"
if A.Length() != 5:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 500 or A.Value(4) != 400 or A.Value(5) != 700:
- print A.Value(1), A.Value(2), A.Value(3), A.Value(4), A.Value(5)
+ print( A.Value(1), A.Value(2), A.Value(3), A.Value(4), A.Value(5))
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger after the first 'undo'!"
# save
file2 = dir + "/test2.hdf"
if res ==0 or A== None :
raise RuntimeError, "AttributeSequenceOfInteger is not found but must be!"
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 500:
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger"
A = A._narrow(SALOMEDS.AttributeSequenceOfInteger)
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 500:
- print "Wrong value of AttributeSequenceOfInteger"
+ print("Wrong value of AttributeSequenceOfInteger")
#----------------------------------------------------------------------
openedStudy=batchmode_geompy.myStudyManager.Open(file2);
A = A._narrow(SALOMEDS.AttributeSequenceOfInteger)
if A.Length() != 5:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 500 or A.Value(4) != 400 or A.Value(5) != 700:
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger after the first 'undo'!"
A.SetValue("AttributesTesting")
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
batchmode_geompy.myBuilder.CommitCommand()
#===========================================================
res, A = batchmode_geompy.myBuilder.FindAttribute(child, "AttributeComment")
-print "res = ", res
+print("res = ", res)
if A != None :
- print " AttributeComment was found"
+ print(" AttributeComment was found")
else:
- print " AttributeComment is not found. It's correct"
+ print(" AttributeComment is not found. It's correct")
attributes=[]
length = len(attributes)
-print "Attributes number = ", length
-print attributes
+print("Attributes number = ", length)
+print(attributes)
for i in range(0, length) :
attr = attributes[i]
if attr is None :
- print i,"None item of object attributes list"
+ print(i,"None item of object attributes list")
if length != 5 :
raise RuntimeError, "Wrong number of attributes"
N32.Prepend(N31)
N33.InsertAfter(N32)
N33.Append(N34)
-print "------------- ", N1, " ------------- "
-print "N1.Label() = ", N1.Label() , "IsRoot() = ", N1.IsRoot(), "Depth() = ", N1.Depth()
-print "N11.Label() = ", N11.Label() , "IsRoot() = ", N11.IsRoot(), "Depth() = ", N11.Depth()
-print "N111.Label() = ", N111.Label() , "IsRoot() = ", N111.IsRoot(), "Depth() = ", N111.Depth()
-print "N2.Label() = ", N2.Label() , "IsRoot() = ", N2.IsRoot(), "Depth() = ", N2.Depth()
-print "N3.Label() = ", N3.Label() , "IsRoot() = ", N3.IsRoot(), "Depth() = ", N3.Depth()
-print "N31.Label() = ", N31.Label() , "IsRoot() = ", N31.IsRoot(), "Depth() = ", N31.Depth()
-print "N32.Label() = ", N32.Label() , "IsRoot() = ", N32.IsRoot(), "Depth() = ", N32.Depth()
-print "N321.Label() = ", N321.Label() , "IsRoot() = ", N321.IsRoot(), "Depth() = ", N321.Depth()
-print "N33.Label() = ", N33.Label() , "IsRoot() = ", N33.IsRoot(), "Depth() = ", N33.Depth()
-print "N34.Label() = ", N34.Label() , "IsRoot() = ", N34.IsRoot(), "Depth() = ", N34.Depth()
-print "N1.IsRoot()=", N1.IsRoot()
-
-print "N1.HasNext() = ",N1.HasNext()
+print("------------- ", N1, " ------------- ")
+print("N1.Label() = ", N1.Label() , "IsRoot() = ", N1.IsRoot(), "Depth() = ", N1.Depth())
+print("N11.Label() = ", N11.Label() , "IsRoot() = ", N11.IsRoot(), "Depth() = ", N11.Depth())
+print("N111.Label() = ", N111.Label() , "IsRoot() = ", N111.IsRoot(), "Depth() = ", N111.Depth())
+print("N2.Label() = ", N2.Label() , "IsRoot() = ", N2.IsRoot(), "Depth() = ", N2.Depth())
+print("N3.Label() = ", N3.Label() , "IsRoot() = ", N3.IsRoot(), "Depth() = ", N3.Depth())
+print("N31.Label() = ", N31.Label() , "IsRoot() = ", N31.IsRoot(), "Depth() = ", N31.Depth())
+print("N32.Label() = ", N32.Label() , "IsRoot() = ", N32.IsRoot(), "Depth() = ", N32.Depth())
+print("N321.Label() = ", N321.Label() , "IsRoot() = ", N321.IsRoot(), "Depth() = ", N321.Depth())
+print("N33.Label() = ", N33.Label() , "IsRoot() = ", N33.IsRoot(), "Depth() = ", N33.Depth())
+print("N34.Label() = ", N34.Label() , "IsRoot() = ", N34.IsRoot(), "Depth() = ", N34.Depth())
+print("N1.IsRoot()=", N1.IsRoot())
+
+print("N1.HasNext() = ",N1.HasNext())
if N1.HasNext():
- print N1.Next().Label()
+ print(N1.Next().Label())
-print "N32.HasPrevious() = ",N32.HasPrevious()
+print("N32.HasPrevious() = ",N32.HasPrevious())
if N32.HasPrevious():
- print N32.GetPrevious().Label()
+ print(N32.GetPrevious().Label())
-print "N111.HasFirst()=",N111.HasFirst()
-print "N111.HasFather()=",N111.HasFather()
+print("N111.HasFirst()=",N111.HasFirst())
+print("N111.HasFather()=",N111.HasFather())
if N111.HasFather() :
- print "N111.GetFather().Label()=",N111.GetFather().Label()
+ print("N111.GetFather().Label()=",N111.GetFather().Label())
subShapeList = batchmode_geompy.SubShapeAll(box,ShapeType["Face"])
face=subShapeList[0]
name = "box_face"
-print name
+print(name)
idface= batchmode_geompy.addToStudyInFather(box,face,name)
# ---- add shell from box in study
subShellList= batchmode_geompy.SubShapeAll(box,ShapeType["Shell"])
shell = subShellList[0]
name = "box_shell"
-print name
+print(name)
idshell= batchmode_geompy.addToStudyInFather(box,shell,name)
# ---- add first edge of face in study
edgeList = batchmode_geompy.SubShapeAll(face,ShapeType["Edge"])
edge=edgeList[0];
name = "face_edge"
-print name
+print(name)
idedge= batchmode_geompy.addToStudyInFather(face,edge,name)
# ---- launch SMESH, init a Mesh with the box
# ---- create Hypothesis
-print "-------------------------- create Hypothesis ----------------------"
-print "-------------------------- LocalLength"
+print("-------------------------- create Hypothesis ----------------------")
+print("-------------------------- LocalLength")
hyp1 = smesh.CreateHypothesis("LocalLength", batchmode_geompy.myStudyId )
hypLen1 = hyp1._narrow(SMESH.SMESH_LocalLength)
hypLen1.SetLength(100)
-print hypLen1.GetName()
-print hypLen1.GetId()
-print hypLen1.GetLength()
+print(hypLen1.GetName())
+print(hypLen1.GetId())
+print(hypLen1.GetLength())
idlength = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypLen1) );
batchmode_smesh.SetName(idlength, "Local_Length_100");
-print "-------------------------- NumberOfSegments"
+print("-------------------------- NumberOfSegments")
hyp2 = smesh.CreateHypothesis("NumberOfSegments", batchmode_geompy.myStudyId )
hypNbSeg1=hyp2._narrow(SMESH.SMESH_NumberOfSegments)
hypNbSeg1.SetNumberOfSegments(7)
-print hypNbSeg1.GetName()
-print hypNbSeg1.GetId()
-print hypNbSeg1.GetNumberOfSegments()
+print(hypNbSeg1.GetName())
+print(hypNbSeg1.GetId())
+print(hypNbSeg1.GetNumberOfSegments())
idseg = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypNbSeg1) );
batchmode_smesh.SetName(idseg, "NumberOfSegments_7");
-print "-------------------------- MaxElementArea"
+print("-------------------------- MaxElementArea")
hyp3 = smesh.CreateHypothesis("MaxElementArea", batchmode_geompy.myStudyId)
hypArea1=hyp3._narrow(SMESH.SMESH_MaxElementArea)
hypArea1.SetMaxElementArea(2500)
-print hypArea1.GetName()
-print hypArea1.GetId()
-print hypArea1.GetMaxElementArea()
+print(hypArea1.GetName())
+print(hypArea1.GetId())
+print(hypArea1.GetMaxElementArea())
idarea1 = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypArea1) );
batchmode_smesh.SetName(idarea1, "MaxElementArea_2500");
-print "-------------------------- MaxElementArea"
+print("-------------------------- MaxElementArea")
hyp3 = smesh.CreateHypothesis("MaxElementArea", batchmode_geompy.myStudyId)
hypArea2 = hyp3._narrow(SMESH.SMESH_MaxElementArea)
hypArea2.SetMaxElementArea(500)
-print hypArea2.GetName()
-print hypArea2.GetId()
-print hypArea2.GetMaxElementArea()
+print(hypArea2.GetName())
+print(hypArea2.GetId())
+print(hypArea2.GetMaxElementArea())
idarea2 = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypArea2) );
batchmode_smesh.SetName(idarea2, "MaxElementArea_500");
-print "-------------------------- Regular_1D"
+print("-------------------------- Regular_1D")
alg1 = smesh.CreateHypothesis("Regular_1D", batchmode_geompy.myStudyId)
algo1 = alg1._narrow(SMESH.SMESH_Algo)
listHyp = algo1.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
+ print(hyp)
algoReg=alg1._narrow(SMESH.SMESH_Regular_1D)
-print algoReg.GetName()
-print algoReg.GetId()
+print(algoReg.GetName())
+print(algoReg.GetId())
idreg = batchmode_smesh.AddNewAlgorithms( orb.object_to_string(algoReg) );
batchmode_smesh.SetName(idreg, "Regular_1D");
-print "-------------------------- MEFISTO_2D"
+print("-------------------------- MEFISTO_2D")
alg2 = smesh.CreateHypothesis("MEFISTO_2D", batchmode_geompy.myStudyId)
algo2 = alg2._narrow(SMESH.SMESH_Algo)
listHyp=algo2.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
+ print(hyp)
algoMef=alg2._narrow(SMESH.SMESH_MEFISTO_2D)
-print algoMef.GetName()
-print algoMef.GetId()
+print(algoMef.GetName())
+print(algoMef.GetId())
idmef = batchmode_smesh.AddNewAlgorithms( orb.object_to_string(algoMef) );
batchmode_smesh.SetName(idmef, "MEFISTO_2D");
# ---- add hypothesis to edge
-print "-------------------------- add hypothesis to edge"
+print("-------------------------- add hypothesis to edge")
edge = batchmode_geompy.IDToObject(idedge)
submesh = mesh.GetElementsOnShape(edge)
ret = mesh.AddHypothesis(edge,algoReg)
-print ret
+print(ret)
ret=mesh.AddHypothesis(edge,hypLen1)
-print ret
+print(ret)
idsm1 = batchmode_smesh.AddSubMeshOnShape( idmesh,
idedge,
batchmode_smesh.SetAlgorithms( idsm1, idreg );
batchmode_smesh.SetHypothesis( idsm1, idlength );
-print "-------------------------- add hypothesis to face"
+print("-------------------------- add hypothesis to face")
face=batchmode_geompy.IDToObject(idface)
submesh=mesh.GetElementsOnShape(face)
ret=mesh.AddHypothesis(face,hypArea2)
-print ret
+print(ret)
idsm2 = batchmode_smesh.AddSubMeshOnShape( idmesh,
idface,
# ---- add hypothesis to box
-print "-------------------------- add hypothesis to box"
+print("-------------------------- add hypothesis to box")
box=batchmode_geompy.IDToObject(idbox)
submesh=mesh.GetElementsOnShape(box)
ret=mesh.AddHypothesis(box,algoReg)
-print ret
+print(ret)
ret=mesh.AddHypothesis(box,hypNbSeg1)
-print ret
+print(ret)
ret=mesh.AddHypothesis(box,algoMef)
-print ret
+print(ret)
ret=mesh.AddHypothesis(box,hypArea1)
-print ret
+print(ret)
batchmode_smesh.SetAlgorithms( idmesh, idreg );
batchmode_smesh.SetHypothesis( idmesh, idseg );
# ---- compute box
-print "-------------------------- compute box"
+print("-------------------------- compute box")
ret=smesh.Compute(mesh,box)
-print ret
+print(ret)
log=mesh.GetLog(0); # no erase trace
for linelog in log:
- print linelog
+ print(linelog)
#=======================================================
if dir == None:
raise RuntimeError, "SUPERV_ROOT_DIR is not defined"
xmlfile = dir +"/examples/GraphEssai.xml"
-print "--------------\n"+xmlfile+"\n--------------\n"
+print("--------------\n"+xmlfile+"\n--------------\n")
myGraph = Graph ( xmlfile )
# This DataFlow is "valid" : no loop, correct links between Nodes etc...
-print myGraph.IsValid()
+print(myGraph.IsValid())
# Get Nodes
myGraph.PrintNodes()
Divz = Div.Port('z')
# This DataFlow is "executable" : all pending Ports are defined with Datas
-print myGraph.IsExecutable()
+print(myGraph.IsExecutable())
# Starts only execution of that DataFlow and gets control immediatly
-print myGraph.Run()
+print(myGraph.Run())
# That DataFlow is running ==> 0 (false)
-print myGraph.IsDone()
+print(myGraph.IsDone())
# Events of execution :
aStatus,aNode,anEvent,aState = myGraph.Event()
while aStatus :
- print aNode.Thread(),aNode.SubGraph(),aNode.Name(),anEvent,aState
+ print(aNode.Thread(),aNode.SubGraph(),aNode.Name(),anEvent,aState)
aStatus,aNode,anEvent,aState = myGraph.Event()
-print myGraph.IsDone()
+print(myGraph.IsDone())
# Wait for Completion (but it is already done after event loop ...)
-print "Done : ",myGraph.DoneW()
+print("Done : ",myGraph.DoneW())
# Get result
-print "Result : ",Divz.ToString()
+print("Result : ",Divz.ToString())
# Intermediate results :
-print "Intermediate Result Add\z : ",Addz.ToString()
-print "Intermediate Result Sub\z : ",Subz.ToString()
-print "Intermediate Result Mul\z : ",Mulz.ToString()
+print("Intermediate Result Add\z : ",Addz.ToString())
+print("Intermediate Result Sub\z : ",Subz.ToString())
+print("Intermediate Result Mul\z : ",Mulz.ToString())
-print " "
-#print "Type : print myGraph.IsDone()"
-#print " If execution is finished ==> 1 (true)"
+print(" ")
+#print("Type : print(myGraph.IsDone()")
+#print(" If execution is finished ==> 1 (true)")
res=myGraph.IsDone()
if res != 1:
raise RuntimeError, "myGraph.Run() is not done"
-print " "
-print "Type : print Divz.ToString()"
-print " You will get the result"
+print(" ")
+print("Type : print(Divz.ToString()")
+print(" You will get the result")
Divz.ToString()
-print " "
-print "Type : myGraph.PrintPorts()"
-print " to see input and output values of the graph"
+print(" ")
+print("Type : myGraph.PrintPorts()")
+print(" to see input and output values of the graph")
myGraph.PrintPorts()
-print " "
-print "Type : Add.PrintPorts()"
+print(" ")
+print("Type : Add.PrintPorts()")
Add.PrintPorts()
-print "Type : Sub.PrintPorts()"
+print("Type : Sub.PrintPorts()")
Sub.PrintPorts()
-print "Type : Mul.PrintPorts()"
+print("Type : Mul.PrintPorts()")
Mul.PrintPorts()
-print "Type : Div.PrintPorts()"
-print " to see input and output values of nodes"
+print("Type : Div.PrintPorts()")
+print(" to see input and output values of nodes")
Div.PrintPorts()
# Export will create newsupervisionexample.xml and the corresponding .py file
if tmpdir is None:
tmpdir="/tmp"
file = tmpdir + "/newsupervisionexample"
-print "--------------\n"+file+"\n--------------\n"
+print("--------------\n"+file+"\n--------------\n")
myGraph.Export(file)
ior = batchmode_geompy.orb.object_to_string(myGraph.G)
addStudy(ior)
GraphName = myGraph.Name()
-print "Befor save ",
+print("Befor save ",)
nodes = myGraph.Nodes()
length_bs = len(nodes)
-print "ListOfNodes length = ", length_bs
+print("ListOfNodes length = ", length_bs)
names=[]
for node in nodes:
names.append(node.Name())
-print names
+print(names)
#=================================
#==================================================
#1. SaveAs
#==================================================
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
batchmode_geompy.myStudyManager.Close(batchmode_geompy.myStudy)
os.mkdir(str + "/test_dir")
#2.==================================================
-print " ------- We rename the file as " + str + "/test_dir/test_new.hdf"
+print(" ------- We rename the file as " + str + "/test_dir/test_new.hdf")
os.rename(file, str+"/test_dir/test_new.hdf")
#==================================================
#3. Open
#==================================================
-print " ------- We try to open " + str + "/test_dir/test_new.hdf"
+print(" ------- We try to open " + str + "/test_dir/test_new.hdf")
try:
openedStudy=batchmode_geompy.myStudyManager.Open(str+"/test_dir/test_new.hdf")
#while aChildIterator.More():
anSObject = aChildIterator.Value()
-#print "iterate: ", anSObject.GetID()
+#print("iterate: ", anSObject.GetID())
res, anAttr=anSObject.FindAttribute("AttributeIOR")
if res :
anAttr=anAttr._narrow(SALOMEDS.AttributeIOR)
Graph=SuperV.getGraph(ior)
ListOfNodes=Graph.Nodes()
length_as= len(ListOfNodes)
- print "ListOfNodes length = ", length_as
+ print("ListOfNodes length = ", length_as)
if length_as != length_bs:
raise RuntimeErrror, "defferent length of nodes after study open"
#aChildIterator.Next()
Graph=SuperV.getGraph(ior)
ListOfNodes=Graph.Nodes()
length_as= len(ListOfNodes)
- print "ListOfNodes length = ", length_as
+ print("ListOfNodes length = ", length_as)
if length_as != length_bs:
raise RuntimeErrror, "defferent length of nodes after study open"
#aChildIterator.Next()
A = A._narrow(SALOMEDS.AttributeStudyProperties)
batchmode_geompy.myBuilder.NewCommand();
-print "A.GetUserName()= ", A.GetUserName()
+print("A.GetUserName()= ", A.GetUserName())
res,mm,hh,dd,mnth,yy=A.GetCreationDate()
-print "A.GetCreationDate() = ", mm,hh,dd,mnth,yy
-print "A.GetCreationMode() = ", A.GetCreationMode()
-print "A.IsModified() = ", A.IsModified()
-print "A.IsLocked() = ", A.IsLocked()
+print("A.GetCreationDate() = ", mm,hh,dd,mnth,yy)
+print("A.GetCreationMode() = ", A.GetCreationMode())
+print("A.IsModified() = ", A.IsModified())
+print("A.IsLocked() = ", A.IsLocked())
if A.IsLocked() == 0 :
- A.SetUserName("tester"); print 'A.SetUserName("tester"), A.GetUserName() = ', A.GetUserName()
- A.SetCreationDate(11,11,11,11,2002); print 'A.SetCreationDate(11,11,11,11,2002), A.GetCreationDate() =', A.GetCreationDate()
- print "A.IsModified() = ", A.IsModified()
+ A.SetUserName("tester"); print('A.SetUserName("tester"), A.GetUserName() = ', A.GetUserName())
+ A.SetCreationDate(11,11,11,11,2002); print('A.SetCreationDate(11,11,11,11,2002), A.GetCreationDate() =', A.GetCreationDate())
+ print("A.IsModified() = ", A.IsModified())
A.SetLocked(1)
#check the transaction result
batchmode_geompy.myBuilder.CommitCommand()
if A.GetUserName() != "tester":
- print 'Control after transaction close : A.GetUserName() = ', A.GetUserName()
+ print('Control after transaction close : A.GetUserName() = ', A.GetUserName())
raise RuntimeError, "Field 'UserName' was not modified but had to!"
# try to make some changes wrapped by transaction
str = "/tmp"
file = str+"/test.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
#4.
myBuilder.NewCommand()
A.SetLocked(0);
-print "A.GetUserName()= ", A.GetUserName()
-print "A.GetCreationDate() = ", A.GetCreationDate()
-print "A.GetCreationMode() = ", A.GetCreationMode()
-print "A.IsModified() = ", A.IsModified()
+print("A.GetUserName()= ", A.GetUserName())
+print("A.GetCreationDate() = ", A.GetCreationDate())
+print("A.GetCreationMode() = ", A.GetCreationMode())
+print("A.IsModified() = ", A.IsModified())
myBuilder.CommitCommand()
#5.
myBuilder.NewCommand()
A.SetUserName("tester1")
myBuilder.CommitCommand()
-print "A.GetUserName()= ", A.GetUserName()
+print("A.GetUserName()= ", A.GetUserName())
#remove the document file
os.remove(file)
A.SetColumn(3,a)
# change attribute values
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
-print "A.PutValue(2,2,625323)"
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
+print("A.PutValue(2,2,625323)")
A.PutValue(625323,2,2)
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
#set Titles
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows()
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns()
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
# set titles
#titles=["11","12","13"]
str = "/tmp"
file = str+"/test.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
A = A._narrow(SALOMEDS.AttributeTableOfInteger)
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows()
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns()
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
titles=["ff","ss","tt"]
A.SetRowTitles(titles)
-print "Rows titles : ", A.GetRowTitles()
+print("Rows titles : ", A.GetRowTitles())
titles=["ww","zz","cc"]
A.SetColumnTitles(titles)
-print "Column titles : ", A.GetColumnTitles()
+print("Column titles : ", A.GetColumnTitles())
A.SetColumn(3,a)
# change attribute values
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
-print "A.PutValue(2,2,625323)"
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
+print("A.PutValue(2,2,625323)")
A.PutValue(625323,2,2)
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
#set Titles
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows() + 1
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns() + 1
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
# set titles
#titles=["11","12","13"]
str = "/tmp"
file = str+"/test.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
A = A._narrow(SALOMEDS.AttributeTableOfReal)
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows() + 1
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns() + 1
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
titles=["ff","ss","tt"]
A.SetRowTitles(titles)
-print "Rows titles : ", A.GetRowTitles()
+print("Rows titles : ", A.GetRowTitles())
titles=["ww","zz","cc"]
A.SetColumnTitles(titles)
-print "Column titles : ", A.GetColumnTitles()
+print("Column titles : ", A.GetColumnTitles())
aStudy.SetContext("/User data/Case1")
#Print the current study context
-print aStudy.GetContext()
+print(aStudy.GetContext())
#Add a sub directory 'aSubCase' to 'Case1' (under the current context)
aBuilder.AddDirectory("aSubCase")
A.Add(0.928e+100)
A.Add(83.287)
-print "initial values ",A.Value(1), A.Value(2), A.Value(3), A.Value(4)
+print("initial values ",A.Value(1), A.Value(2), A.Value(3), A.Value(4))
A.Remove(3)
-print "after remove ", A.Value(1), A.Value(2), A.Value(3)
+print("after remove ", A.Value(1), A.Value(2), A.Value(3))
A.ChangeValue(2,76.265)
-print "after second item change", A.Value(1), A.Value(2), A.Value(3)
+print("after second item change", A.Value(1), A.Value(2), A.Value(3))
if A.Length() != 3:
- print "Error : wrong length of SequenceOfReal"
+ print("Error : wrong length of SequenceOfReal")
if A.Value(1) != 0.0293 or A.Value(2) != 76.265 or A.Value(3) != 83.287:
- print "Error : wrong value of AttributeSequenceOfReal"
+ print("Error : wrong value of AttributeSequenceOfReal")
# save / restore study
#=================================
A = A._narrow(SALOMEDS.AttributeSequenceOfReal)
if A.Length() != 3:
- print "Error : wrong length of SequenceOfReal"
+ print("Error : wrong length of SequenceOfReal")
if A.Value(1) != 0.0293 or A.Value(2) != 76.265 or A.Value(3) != 83.287:
- print "Error : wrong value of AttributeSequenceOfReal"
-print "after restoring ", A.Value(1), A.Value(2), A.Value(3)
+ print("Error : wrong value of AttributeSequenceOfReal")
+print("after restoring ", A.Value(1), A.Value(2), A.Value(3))
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 700:
- print "Wrong value of AttributeSequenceOfInteger"
+ print("Wrong value of AttributeSequenceOfInteger")
# save / restore study
A = A._narrow(SALOMEDS.AttributeSequenceOfInteger)
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 700:
- print "Wrong value of AttributeSequenceOfInteger"
+ print("Wrong value of AttributeSequenceOfInteger")
A.SetValue("AttributesTesting")
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
# save / restore study
raise RuntimeError, "Can't create AttributeName attribute"
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
iter.InitEx(True) # init recursive mode
while iter.More():
c = iter.Value()
- print c.GetID()
+ print(c.GetID())
iter.Next()
pass
# WARN: This may still add duplicate entries to path on
# case-insensitive filesystems
if os.path.isdir(subdir) and subdir not in __path__:
- print "INFO - The directory %s is appended to sys.path" % subdir
+ print("INFO - The directory %s is appended to sys.path" % subdir)
__path__.append(subdir)
extend_path(ROOT_PYTHONPACKAGE_NAME)
\code
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())
...
instance.stop()
\endcode
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)] != '__' \
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)
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")
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,"*")
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
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
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:
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))
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:
AC_MSG_RESULT($swig_ok)
fi
-numpydir=`$PYTHON -c "import numpy;print numpy.get_include()" 2>/dev/null`
+numpydir=`$PYTHON -c "import numpy;print(numpy.get_include())" 2>/dev/null`
if test -d "$numpydir"; then
numpy_ok=yes
PYTHON_INCLUDES="-I$numpydir $PYTHON_INCLUDES"
changequote(,)dnl
py_makefile="`$PYTHON -c '
import sys
-print \"%s/lib/python%s/config/Makefile\"%(sys.exec_prefix, sys.version[:3])'`"
+print(\"%s/lib/python%s/config/Makefile\"%(sys.exec_prefix, sys.version[:3]))'`"
changequote([,])dnl
if test ! -f "$py_makefile"; then
AC_MSG_ERROR([*** Couldn't find the python config makefile. Maybe you are
import sys
ver = sys.version[:3]
pre = sys.exec_prefix
-print \"-L%s/lib/python%s/config\" % (pre, ver),
+print(\"-L%s/lib/python%s/config\" % (pre, ver)),
if ver == \"1.4\":
- print \"-lPython -lObjects -lParser\"
+ print(\"-lPython -lObjects -lParser\")
else:
- print \"-lpython\" + ver
+ print(\"-lpython\" + ver)
changequote([,])dnl
changequote(,)dnl
py_config_in="`$PYTHON -c '
import sys
-print \"%s/lib/python%s/config/config.c.in\"%(sys.exec_prefix, sys.version[:3])'`"
+print(\"%s/lib/python%s/config/config.c.in\"%(sys.exec_prefix, sys.version[:3]))'`"
changequote([,])dnl
if test ! -f "$py_config_in"; then
AC_MSG_ERROR([*** Couldn't find the config.c.in file. Maybe you are
AC_SUBST(PYTHONHOME)
changequote(<<, >>)dnl
- PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
+ PYTHON_VERSION=`$PYTHON -c "import sys; print(sys.version[:3])"`
changequote([, ])dnl
AC_SUBST(PYTHON_VERSION)
dnl to know which OS Python thinks this is.
AC_SUBST(PYTHON_PLATFORM)
- PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"`
+ PYTHON_PLATFORM=`$PYTHON -c "import sys; print(sys.platform)"`
AC_SUBST(PYTHON_SITE)
AC_ARG_WITH(python-site,
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)
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) )
#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 )
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 ))
# -----------------------------------------------------------------------------
-print "Hello world"
+print("Hello world")
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(libSALOME_Comm.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(libSALOME_Comm.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(libSALOME_Comm.i PROPERTIES SWIG_FLAGS "-py3")
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIRS}
(char*)"import_component",
(char*)"s",componentName);
- reason=PyString_AsString(result);
+ reason=PyUnicode_AsUTF8(result);
Py_XDECREF(result);
SCRUTE(reason);
PyGILState_Release(gstate);
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)
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);
}
_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;
+}
+*/
#include "utilities.h"
#include "Container_init_python.hxx"
+#if PY_VERSION_HEX < 0x03050000
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+ wchar_t *res;
+ unsigned char *in;
+ wchar_t *out;
+ size_t argsize = strlen(arg) + 1;
+
+ if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
+ return NULL;
+ res = (wchar_t*) PyMem_RawMalloc(argsize*sizeof(wchar_t));
+ if (!res)
+ return NULL;
+
+ in = (unsigned char*)arg;
+ out = res;
+ while(*in)
+ if(*in < 128)
+ *out++ = *in++;
+ else
+ *out++ = 0xdc00 + *in++;
+ *out = 0;
+ if (size != NULL)
+ *size = out - res;
+ return res;
+}
+#endif
+
void KERNEL_PYTHON::init_python(int argc, char **argv)
{
if (Py_IsInitialized())
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
// 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;
}
from SALOME_utilities import *
-from thread import *
+from _thread import *
#=============================================================================
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
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) ")
#-------------------------------------------------------------------------
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)
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:
#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
#-------------------------------------------------------------------------
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
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)
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
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
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
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)
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]
# 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()
#Block for ever
orb.run()
- if verbose():print "SALOME_ContainerPy_i shutdown"
+ if verbose():print("SALOME_ContainerPy_i shutdown")
#
import sys,traceback,string
import linecache
-import cPickle
+import pickle
import Engines__POA
import SALOME__POA
import SALOME
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):
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()
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))
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()
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(calcium.i PROPERTIES CPLUSPLUS ON)
+SET_SOURCE_FILES_PROPERTIES(calcium.i PROPERTIES SWIG_FLAGS "-py3")
SET(CMAKE_SWIG_FLAGS "-noexcept")
ADD_DEFINITIONS(${OMNIORB_DEFINITIONS} ${BOOST_DEFINITIONS} ${PYTHON_DEFINITIONS} ${NUMPY_DEFINITIONS})
%init
%{
+#include <capsulethunk.h>
// init section
-
#ifdef WITH_NUMPY
import_array()
#endif
{
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");
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";
}
def __init__(self, aDoc):
self.doc = aDoc
def __repr__(self):
- print self.doc
+ print(self.doc)
return "---"
def salome(self):
doc_salome = '''
salome.DumpStudy(study) : Dump a study, given the ior
---
'''
- print doc_salome
+ print(doc_salome)
def geompy(self):
doc_geompy = '''
--- 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 = '''
and GraphExample.xml
---
'''
- print doc_supervision
+ print(doc_supervision)
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]
while ofs <= offset:
a = a + " "
ofs = ofs +1
- print a + ">" + RefSO.GetID()
+ print(a + ">" + RefSO.GetID())
DumpComponent(Study, CSO, offset+2)
#--------------------------------------------------------------------------
SC = itcomp.Value()
itcomp.Next()
name = SC.ComponentDataType()
- print "-> ComponentDataType is " + name
+ print("-> ComponentDataType is " + name)
DumpComponent(Study, SC, 1)
# 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')
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)
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():
def ImportComponentGUI(ComponentName):
libName = "lib" + ComponentName + "_Swig"
command = "from " + libName + " import *"
- exec ( command )
+ exec (command, globals())
constructor = ComponentName + "GUI_Swig()"
command = "gui = " + constructor
- exec ( command )
+ exec (command, globals())
return gui
#--------------------------------------------------------------------------
#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
#--------------------------------------------------------------------------
aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
if not myStudyManager.CanCopy(theSO):
- raise RuntimeError, "<CanCopy> for "+theInfo+" returns false"
+ raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
if not myStudyManager.Copy(theSO):
- raise RuntimeError, "<Copy> for "+theInfo+" returns false"
+ raise RuntimeError("<Copy> for "+theInfo+" returns false")
if not myStudyManager.CanPaste(theSO):
- raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
+ raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
# check: before paste study is not changed check
if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
- raise RuntimeError, "Study is changed before Paste calling for "+theInfo
+ raise RuntimeError("Study is changed before Paste calling for "+theInfo)
aSObj = theSO
if theComponentPaste:
aSObj = theSO.GetFatherComponent()
theInfo = theInfo + "(paste for component)"
if myStudyManager.Paste(aSObj) == None:
- raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
+ raise RuntimeError("<Paste> for "+theInfo+" returns None object")
aNewTree = GetTree(aRoot)
aLen = len(aTree)
for a in range(0,aLen):
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):
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)
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)
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();
myStudyName = myStudy._get_Name()
myStudyId = myStudy._get_StudyId()
-#print myStudyId
+# print(myStudyId)
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"""
#
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
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("salome/kernel/__init__","TEST_serialization")
__author__="gboulant"
__date__ ="$15 avr. 2010 19:44:17$"
-from uiexception import DevelException
+from .uiexception import DevelException
# Most usable class types
TypeString= "".__class__
# 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.
#__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:
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]
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] ) )
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())))
data.anydata = "any value"
data.anydata = True
- print data.integerdata
+ print(data.integerdata)
return True
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():
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():
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():
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():
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():
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")
# \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
## 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.
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
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")
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.
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
"""
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
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():
'SEP',
'OTHER'
])
- print TYPES_LIST.listvalues()
+ print(TYPES_LIST.listvalues())
return True
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:
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:
'MED',
'SMESH'])
- print "VISU in enumerate?", codes.contains("VISU")
+ print("VISU in enumerate?", codes.contains("VISU"))
if (not codes.contains("VISU")):
return True
else:
'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:
'MED',
'SMESH'], offset=20)
- print codes.listvalues()
+ print(codes.listvalues())
if codes.listvalues() != [20, 21, 22, 23, 24]:
return False
return True
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")
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
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
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
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
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():
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)
# 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) :
"""
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
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
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")
import re
-import salome
-from salome.kernel.logger import Logger
from salome.kernel import termcolor
-logger = Logger("salome.kernel.studyedit", color = termcolor.PURPLE)
+from salome.kernel.logger import Logger
+import salome
+
+
+logger = Logger("salome.kernel.studyedit", color=termcolor.PURPLE)
_editors = {}
_DEFAULT_CONTAINER = "FactoryServer"
-# The codec to use for strings that are displayed in Salome study tree is Latin-1
-ENCODING_FOR_SALOME_STUDY = "iso-8859-1"
-
## Return the ID of the active study. In GUI mode, this function is equivalent
# to salome.sg.getActiveStudyId(). Outside GUI, it returns <b> salome.myStudyId </b>
# variable.
"""
if studyId is None:
studyId = getActiveStudyId()
- if not _editors.has_key(studyId):
+ if studyId not in _editors:
_editors[studyId] = StudyEditor(studyId)
return _editors[studyId]
# \return new SObject created in the study.
#
# See \b setItem() for the description of the other parameters.
- def createItem(self, fatherItem, name, fileType = None, fileName = None,
- comment = None, icon = None, IOR = None, typeId = None):
+ def createItem(self, fatherItem, name, fileType=None, fileName=None,
+ comment=None, icon=None, IOR=None, typeId=None):
"""
Create a new object named `name` under `fatherItem` in the study, with
the given attributes. If an object named `name` already exists under
the father object, the new object is created with a new name `name_X`
where X is the first available index.
-
+
:type fatherItem: SObject
:param fatherItem: item under which the new item will be added.
-
+
:return: new SObject created in the study
-
+
See :meth:`setItem` for the description of the other parameters.
"""
aSObject = self.builder.NewObject(fatherItem)
aSObj = aChildIterator.Value()
aChildIterator.Next()
aName = aSObj.GetName()
- if re.match(aNameRE,aName):
+ if re.match(aNameRE, aName):
aTmp = aName[aLength:]
- if re.match(anIdRE,aTmp):
- import string
- anId = string.atol(aTmp[1:])
+ if re.match(anIdRE, aTmp):
+ anId = int(aTmp[1:])
if aMaxId < anId:
aMaxId = anId
pass
pass
pass
pass
-
+
aMaxId = aMaxId + 1
aName = name
if aMaxId > 0:
aName = aName + aDelim + str(aMaxId)
pass
-
+
self.setItem(aSObject, aName, fileType, fileName, comment, icon,
IOR, typeId)
-
+
return aSObject
## Modify the attributes of an item in the study. Unspecified attributes
## Return the name of the object sObject
def getName(self, sObject):
- val = sObject.GetName()
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return sObject.GetName()
## Set the name of the object sObject
def setName(self, sObject, name):
- self.builder.SetName(sObject, name.encode(ENCODING_FOR_SALOME_STUDY))
+ self.builder.SetName(sObject, name)
## Return the comment of the object sObject
def getComment(self, sObject):
- val = sObject.GetComment()
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return sObject.GetComment()
## Set the comment of the object sObject
def setComment(self, sObject, comment):
- self.builder.SetComment(sObject, comment.encode(ENCODING_FOR_SALOME_STUDY))
+ self.builder.SetComment(sObject, comment)
## Return the value of the attribute named \b attributeName on the object
# sObject, or \b default if the attribute doesn't exist.
Return the value of the attribute "AttributeFileType" of the object
`sObject`, or an empty string if it is not set.
"""
- val = self.getAttributeValue(sObject, "AttributeFileType", "")
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return self.getAttributeValue(sObject, "AttributeFileType", "")
## Set the attribute "AttributeFileType" of the object sObject to the
# value value.
value `value`.
"""
self.setAttributeValue(sObject, "AttributeFileType",
- value.encode(ENCODING_FOR_SALOME_STUDY))
+ value)
## Return the value of the attribute "AttributeExternalFileDef" of the
# object sObject, or an empty string if it is not set.
Return the value of the attribute "AttributeExternalFileDef" of the
object `sObject`, or an empty string if it is not set.
"""
- val = self.getAttributeValue(sObject, "AttributeExternalFileDef", "")
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return self.getAttributeValue(sObject, "AttributeExternalFileDef", "")
## Set the attribute "AttributeExternalFileDef" of the object sObject
# to the value value.
to the value `value`.
"""
self.setAttributeValue(sObject, "AttributeExternalFileDef",
- value.encode(ENCODING_FOR_SALOME_STUDY))
+ value)
## Return the value of the attribute "AttributePixMap" of the object
# sObject, or an empty string if it is not set.
found, attr = self.builder.FindAttribute(sObject, "AttributePixMap")
if found and attr.HasPixMap():
value = attr.GetPixMap()
- return unicode(value, ENCODING_FOR_SALOME_STUDY)
+ return value
## Set the attribute "AttributePixMap" of the object sObject to the
# value value.
value `value`.
"""
attr = self.builder.FindOrCreateAttribute(sObject, "AttributePixMap")
- attr.SetPixMap(value.encode(ENCODING_FOR_SALOME_STUDY))
+ attr.SetPixMap(value)
pathname = os.path.join(rootpath, f)
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):
callback(pathname, **kwargs)
else:
# Unknown file type, print a message
- print 'Skipping %s' % pathname
+ print('Skipping %s' % pathname)
#
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)
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("syshelper", "TEST_findFiles")
unittester.run("syshelper", "TEST_walktree")
# import sys
# from salome.kernel import termcolor
# if termcolor.canDisplayColor(sys.stdout):
-# print termcolor.makeColoredMessage("Hello world!", termcolor.BLUE)
+# print(termcolor.makeColoredMessage("Hello world!", termcolor.BLUE))
# else:
-# print "Hello world!"
+# print("Hello world!")
# \endcode
# \}
import sys
from salome.kernel import termcolor
if termcolor.canDisplayColor(sys.stdout):
- print termcolor.makeColoredMessage("Hello world!", termcolor.BLUE)
+ print(termcolor.makeColoredMessage("Hello world!", termcolor.BLUE))
else:
- print "Hello world!"
+ print("Hello world!")
"""
"""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
__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):
# Basic use cases and unit tests
# ==============================================================================
#
-from uiexception import UiException
+from .uiexception import UiException
def TEST_getName():
testdata = TestData()
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():
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():
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():
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
# 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")
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()
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
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)
"""
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):
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):
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)
def myCallbackFunction():
- print "myCallbackFunction: the job is ended"
+ print("myCallbackFunction: the job is ended")
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()
__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
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")
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
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
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]
shared_imported[mname]=mod
# Salome modification end
- elif _partialModules.has_key(mname):
+ elif mname in _partialModules:
mod = _partialModules[mname]
# Salome modification start
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:
# 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__)
def createAndDisplayGO( *args, **kwargs ):
pass
-
#--------------------------------------------------------------------------
def UpdateViewer():
- pass
-
+ pass
#--------------------------------------------------------------------------
def setDisplayMode(objId, mode):
if IN_SALOME_GUI:
libName = "lib" + ComponentName + "_Swig"
command = "from " + libName + " import *"
- exec ( command )
+ exec (command, globals())
constructor = ComponentName + "_Swig()"
command = "gui = " + constructor
- exec ( command )
- return gui
+ exec (command, globals())
+ return gui # @UndefinedVariable
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
#--------------------------------------------------------------------------
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"
- return none
+ 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 ""
#--------------------------------------------------------------------------
pass
def GetVariableNames(self):
- return self.kwargs.keys()
+ return list(self.kwargs.keys())
def IsVariable(self, variableName):
return variableName in self.kwargs
pass
try:
aResult = eval(aResult)
- except Exception, e:
+ except Exception as e:
msg = str(e)
msg += "\n"
msg += "A problem occurs while parsing "
exception
"""
import omniORB
-import cPickle
+import pickle
import SALOME
import Engines
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
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
find,RefSO = CSO.ReferencedObject()
if find:
a=a+":"+RefSO.GetID()
- print a
+ print(a)
DumpComponent(Study, CSO, Builder,offset+2)
it.Next()
while itcomp.More():
SC = itcomp.Value()
name = SC.ComponentDataType()
- print "-> ComponentDataType is " + name
+ print("-> ComponentDataType is " + name)
DumpComponent(Study, SC,Builder, 1)
itcomp.Next()
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)
aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
if not myStudyManager.CanCopy(theSO):
- raise RuntimeError, "<CanCopy> for "+theInfo+" returns false"
+ raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
if not myStudyManager.Copy(theSO):
- raise RuntimeError, "<Copy> for "+theInfo+" returns false"
+ raise RuntimeError("<Copy> for "+theInfo+" returns false")
if not myStudyManager.CanPaste(theSO):
- raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
+ raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
# check: before paste study is not changed check
if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
- raise RuntimeError, "Study is changed before Paste calling for "+theInfo
+ raise RuntimeError("Study is changed before Paste calling for "+theInfo)
aSObj = theSO
if theComponentPaste:
aSObj = theSO.GetFatherComponent()
theInfo = theInfo + "(paste for component)"
if myStudyManager.Paste(aSObj) == None:
- raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
+ raise RuntimeError("<Paste> for "+theInfo+" returns None object")
aNewTree = GetTree(aRoot)
aLen = len(aTree)
for a in range(0,aLen):
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")
#--------------------------------------------------------------------------
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:
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
#--------------------------------------------------------------------------
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
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
#--------------------------------------------------------------------------
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
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)
# 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
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)
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
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" );
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
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")
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
#====================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'
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,
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
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 )
# 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
text = f.read()
f.close()
self.assertEqual(text, content)
- except IOError,ex:
+ except IOError as ex:
self.fail("IO exception:" + str(ex));
##############################
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
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")
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
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
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
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")
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
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")
# 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
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(libSALOME_LifeCycleCORBA.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(libSALOME_LifeCycleCORBA.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(libSALOME_LifeCycleCORBA.i PROPERTIES SWIG_FLAGS "-py3")
ADD_DEFINITIONS(${OMNIORB_DEFINITIONS})
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIRS}
${PTHREAD_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PROJECT_BINARY_DIR}/salome_adm
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
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
# Module : SALOME
# $Header$
#
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
import subprocess
import runSalome
import setenv
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
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()
enginePy=lcc.FindComponent(myContainerparamsPy,'SALOME_TestComponentPy')
enginePy.Coucou(1)
except :
- print 'ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed'
+ print('ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed')
#define PY_SSIZE_T_MIN INT_MIN
#endif
-//--- from omniORBpy.h (not present on Debian Sarge packages)
-
-struct omniORBpyAPI {
-
- PyObject* (*cxxObjRefToPyObjRef)(const CORBA::Object_ptr cxx_obj,
- CORBA::Boolean hold_lock);
- // Convert a C++ object reference to a Python object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- CORBA::Object_ptr (*pyObjRefToCxxObjRef)(PyObject* py_obj,
- CORBA::Boolean hold_lock);
- // Convert a Python object reference to a C++ object reference.
- // Raises BAD_PARAM if the Python object is not an object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
-
- omniORBpyAPI();
- // Constructor for the singleton. Sets up the function pointers.
-};
-
-omniORBpyAPI* api;
+#include <Python.h>
+#include <omniORBpy.h>
+omniORBpyAPI* api=0;
%}
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_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
%}
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"
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)
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import sys, os,signal,string,commands
+import sys, os,signal,subprocess
def getCurrentPort():
fic=os.environ['OMNIORB_CONFIG']
with open(fic,'r') as f:
line=f.readline()
- port=string.split(line,':')[-1][0:4]
+ port=line.split(':')[-1][0:4]
return port
port = getCurrentPort()
try:
from PortManager import releasePort
- print "### release current port:", port
+ print("### release current port:", port)
releasePort(port)
except:
pass
"""
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]
+ pid=output_com.split()[0]
os.kill(int(pid),signal.SIGKILL)
except:
- print "killNamingService failed."
+ print("killNamingService failed.")
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
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;
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
# print error message
#--------------------------------------------------
def error (message):
- print "ERROR : ", message
+ print("ERROR : ", message)
#--------------------------------------------------
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 != '':
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)
## 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())
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)
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):
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):
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)
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')
if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
os.unlink(CatalogFileName_old)
- print
+ print()
if __name__ == "__main__":
- print
- print "Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,multistudy=<component_multistudy>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>"
- print
+ print()
+ print("Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,multistudy=<component_multistudy>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>")
+ print()
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(NOTIFICATION.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(NOTIFICATION.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(NOTIFICATION.i PROPERTIES SWIG_FLAGS "-py3")
SET_SOURCE_FILES_PROPERTIES(NOTIFICATIONPYTHON_wrap.cxx PROPERTIES COMPILE_FLAGS "${OMNIORB_DEFINITIONS} -DHAVE_CONFIG_H")
INCLUDE_DIRECTORIES(
#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
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" )
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)
_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):
#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):
#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" )
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=[]
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):
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)
# 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
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;
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;
# 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
sfp << _GetNoteBookAccess(aStudyVar) << std::endl;
// extend sys.path with the directory where the script is being dumped to
- sfp << "sys.path.insert( 0, r\'" << thePath << "\')" << std::endl << std::endl;
+ sfp << "sys.path.insert(0, r\'" << thePath << "\')" << std::endl << std::endl;
// dump NoteBook variables
sfp << _GetStudyVariablesScript();
std::string SALOMEDSImpl_Study::GetDumpStudyComment(const char* theComponentName)
{
std::stringstream txt;
- txt << "# -*- coding: utf-8 -*-" << std::endl << std::endl;
+ txt << "#!/usr/bin/env python" << std::endl << std::endl;
txt << "###" << std::endl;
txt << "### This file is generated automatically by SALOME v"
<< KERNEL_VERSION_STR
# 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
# 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
# dict,list,tuple,int,float,str
import SALOME
-import cPickle
+import pickle
class List(object):
def __init__(self,varPtr,isTemporaryVar=False):
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
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(),))
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
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(),))
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
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(),))
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
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(),))
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)
std::size_t DataScopeServerBase::COUNTER=0;
+#if PY_VERSION_HEX < 0x03050000
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+ wchar_t *res;
+ unsigned char *in;
+ wchar_t *out;
+ size_t argsize = strlen(arg) + 1;
+
+ if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
+ return NULL;
+ res = (wchar_t*) PyMem_RawMalloc(argsize*sizeof(wchar_t));
+ if (!res)
+ return NULL;
+
+ in = (unsigned char*)arg;
+ out = res;
+ while(*in)
+ if(*in < 128)
+ *out++ = *in++;
+ else
+ *out++ = 0xdc00 + *in++;
+ *out = 0;
+ if (size != NULL)
+ *size = out - res;
+ return res;
+}
+#endif
+
void DataScopeKiller::shutdown()
{
Py_Finalize();
{
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)
}
_locals=PyDict_New();
PyObject *tmp(PyList_New(0));
- _pickler=PyImport_ImportModuleLevel(const_cast<char *>("cPickle"),_globals,_locals,tmp,-1);
+ _pickler=PyImport_ImportModuleLevel(const_cast<char *>("pickle"),_globals,_locals,tmp,-1);
}
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);
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]) !";
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]) !";
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);
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 << " )";
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"));
PyObject *PickelizedPyObjServer::GetPyObjFromPickled(const std::vector<unsigned char>& pickledData, DataScopeServerBase *dsb)
{
std::size_t sz(pickledData.size());
- PyObject *pickledDataPy(PyString_FromStringAndSize(NULL,sz));// agy : do not use PyString_FromString because std::string hides a vector of byte.
- char *buf(PyString_AsString(pickledDataPy));// this buf can be used thanks to python documentation.
+ PyObject *pickledDataPy(PyBytes_FromStringAndSize(NULL,sz));// agy : do not use PyUnicode_FromString because std::string hides a vector of byte.
+ char *buf(PyBytes_AS_STRING(pickledDataPy));// this buf can be used thanks to python documentation.
const unsigned char *inBuf(&pickledData[0]);
std::copy(inBuf,inBuf+sz,buf);
PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"loads"));
{
PyObject *args(PyTuple_New(2));
PyTuple_SetItem(args,0,obj);
- PyTuple_SetItem(args,1,PyInt_FromLong(2));// because "assert(cPickle.HIGHEST_PROTOCOL is 2)"
+ PyTuple_SetItem(args,1,PyLong_FromLong(2));// because "assert(cPickle.HIGHEST_PROTOCOL is 2)"
PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"dumps"));
PyObject *retPy(PyObject_CallObject(selfMeth,args));
Py_XDECREF(selfMeth);
Py_XDECREF(args);
- std::size_t sz(PyString_Size(retPy));
+ std::size_t sz(PyBytes_Size(retPy));
std::string ret(sz,'\0');
- const char *buf(PyString_AsString(retPy));
+ const char *buf(PyBytes_AS_STRING(retPy));
char *inBuf(const_cast<char *>(ret.c_str()));
for(std::size_t i=0;i<sz;i++)
inBuf[i]=buf[i];
throw Exception("PickelizedPyObjServer::setNewPyObj : trying to assign a NULL pyobject in this !");
if(obj==_self)
return ;
- if(PyList_Check(obj)==0 && PyDict_Check(obj)==0 && PyTuple_Check(obj)==0 && PyString_Check(obj)==0 && PyInt_Check(obj)==0 && PyBool_Check(obj)==0 && PyFloat_Check(obj)==0 && obj!=Py_None)
- throw Exception("PickelizedPyObjServer::setNewPyObj : Supported python types are [list,tuple,dict,str,int,bool,float,None] !");
+ if(PyList_Check(obj)==0 && PyDict_Check(obj)==0 && PyTuple_Check(obj)==0 && PyBytes_Check(obj)==0 && PyLong_Check(obj)==0 && PyBool_Check(obj)==0 && PyFloat_Check(obj)==0 && obj!=Py_None)
+ throw Exception("PickelizedPyObjServer::setNewPyObj : Supported python types are [list,tuple,dict,bytes,int,bool,float,None] !");
if(_self)
{
PyObject *selfType(PyObject_Type(_self));
def _raiseNow(strCont):
raise Exception("The method %s has been called whereas it is an interface !"%strCont)
-class WrappedType(object):
+class WrappedType(object, metaclass=abc.ABCMeta):
""" Here definition of an interface in python."""
- __metaclass__=abc.ABCMeta
@abc.abstractmethod
def ptr(self):
_raiseNow("ptr")
# Author : Anthony Geay
import SALOME
-import cPickle
+import pickle
import SALOMEWrappedStdType
class InvokatorStyle(object):
return self._var_ptr.ptr()
def local_copy(self):
- return cPickle.loads(self._var_ptr.ptr().fetchSerializedContent())
+ return pickle.loads(self._var_ptr.ptr().fetchSerializedContent())
def __str__(self):
return self.local_copy().__str__()
def assign(self,elt):
ptrCorba=self._var_ptr.ptr()
assert(isinstance(ptrCorba,SALOME._objref_PickelizedPyObjRdWrServer))
- st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+ st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
ptrCorba.setSerializedContent(st)
pass
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
""" Returns a client that allows to handle a remote corba ref of a global var easily.
"""
assert(isinstance(objCorba,SALOME._objref_PickelizedPyObjServer))
- v=cPickle.loads(objCorba.fetchSerializedContent())
+ v=pickle.loads(objCorba.fetchSerializedContent())
if v is None:
objCorba.UnRegister()
return None
salome.salome_init()
dsm=salome.naming_service.Resolve("/DataServerManager")
d2s,isCreated=dsm.giveADataScopeCalled(scopeName)
- return GetHandlerFromRef(d2s.createRdOnlyVar(varName,cPickle.dumps(value,cPickle.HIGHEST_PROTOCOL)),False)
+ return GetHandlerFromRef(d2s.createRdOnlyVar(varName,pickle.dumps(value,pickle.HIGHEST_PROTOCOL)),False)
def CreateRdExtGlobalVar(value,varName,scopeName):
import salome
salome.salome_init()
dsm=salome.naming_service.Resolve("/DataServerManager")
d2s,isCreated=dsm.giveADataScopeCalled(scopeName)
- return GetHandlerFromRef(d2s.createRdExtVar(varName,cPickle.dumps(value,cPickle.HIGHEST_PROTOCOL)),False)
+ return GetHandlerFromRef(d2s.createRdExtVar(varName,pickle.dumps(value,pickle.HIGHEST_PROTOCOL)),False)
def GetHandlerFromName(varName,scopeName):
import salome
import SALOME
import salome
import unittest
-import cPickle
+import pickle
import gc
import time
import multiprocessing as mp
def obj2Str(obj):
- return cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL)
+ return pickle.dumps(obj,pickle.HIGHEST_PROTOCOL)
def str2Obj(strr):
- return cPickle.loads(strr)
+ return pickle.loads(strr)
def generateKey(varName,scopeName):
dsm=salome.naming_service.Resolve("/DataServerManager")
dss,isCreated=dsm.giveADataScopeTransactionCalled(scopeName)
proc=subprocess.Popen(["python",fname],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err=proc.communicate()
if proc.returncode!=0:
- print out
- print err
+ print(out)
+ print(err)
return proc.returncode
class SalomeSDSTest(unittest.TestCase):
#
nbProc=8
pool=mp.Pool(processes=nbProc)
- asyncResult=pool.map_async(work,[(i,varName,scopeName) for i in xrange(nbProc)])
+ asyncResult=pool.map_async(work,[(i,varName,scopeName) for i in range(nbProc)])
self.assertEqual(asyncResult.get(),nbProc*[0]) # <- the big test is here !
dsm.removeDataScope(scopeName)
import salome
import SALOME
-import cPickle
+import pickle
import gc
import SalomeSDSClt
a=d2s.createRdWrVar("str","c")
assert(a.getVarName()=="c")
#
-a.setSerializedContent(cPickle.dumps(st,cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==st)
-assert(cPickle.loads(a.fetchSerializedContent())==st)
-assert(cPickle.loads(d2s.retrieveVar("c").fetchSerializedContent())==st)
+a.setSerializedContent(pickle.dumps(st,pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==st)
+assert(pickle.loads(a.fetchSerializedContent())==st)
+assert(pickle.loads(d2s.retrieveVar("c").fetchSerializedContent())==st)
assert(isinstance(d2s.retrieveVar("c"),SALOME._objref_PickelizedPyObjRdWrServer))
assert(dsm.listScopes()==['Default','tonyy'])
dsm.createDataScope("S2")
#
sname="S7"
dsm=salome.naming_service.Resolve("/DataServerManager")
-st=cPickle.dumps([],cPickle.HIGHEST_PROTOCOL)
+st=pickle.dumps([],pickle.HIGHEST_PROTOCOL)
a=dsm.giveADataScopeCalled(sname)[0].createRdWrVar("list","a")
dsm.giveADataScopeCalled(sname)
-a.setSerializedContent(cPickle.dumps([0,],cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==[0,])
+a.setSerializedContent(pickle.dumps([0,],pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[0,])
a.setSerializedContent(st)
-assert(cPickle.loads(a.fetchSerializedContent())==[])
-tmp=a.invokePythonMethodOn("append",cPickle.dumps((0,),cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==[0])
-for i in xrange(0,1000):
- tmp=a.invokePythonMethodOn("append",cPickle.dumps((i,),cPickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[])
+tmp=a.invokePythonMethodOn("append",pickle.dumps((0,),pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[0])
+for i in range(0,1000):
+ tmp=a.invokePythonMethodOn("append",pickle.dumps((i,),pickle.HIGHEST_PROTOCOL))
pass
dsm.removeDataScope(sname)
#
d2s.createRdWrVar("list","a")
a=SalomeSDSClt.GetHandlerFromRef(dsm.retriveDataScope(sname).retrieveVar("a"))
a.append(1)
-for i in xrange(1000):
+for i in range(1000):
a.append(i)
pass
assert(sum(a.local_copy())==499501)
import SALOME
-import cPickle
+import pickle
import salome
import sys
varName="a"
def obj2Str(obj):
- return cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL)
+ return pickle.dumps(obj,pickle.HIGHEST_PROTOCOL)
def str2Obj(strr):
- return cPickle.loads(strr)
+ return pickle.loads(strr)
def waitKey():
dsm=salome.naming_service.Resolve("/DataServerManager")
# 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
class SALOME_TestComponentPy( Engines__POA.TestComponent, SALOME_ComponentPy_i):
def Coucou(self, val):
- print "SALOME_TestComponentPy Coucou ", val
- result = "result from SALOME_TestComponentPy Coucou " + `val`
+ print("SALOME_TestComponentPy Coucou ", val)
+ result = "result from SALOME_TestComponentPy Coucou " + repr(val)
return result
def __init__(self, orb, poa, contID, containerName, instanceName, interfaceName):
notif = False
SALOME_ComponentPy_i.__init__(self, orb, poa, contID, containerName,
instanceName, interfaceName, notif)
- print "SALOME_TestComponentPy::__init__"
+ print("SALOME_TestComponentPy::__init__")
rootContext = obj._narrow(CosNaming.NamingContext)
if rootContext is None:
- print "Name Service Reference is invalid"
+ print("Name Service Reference is invalid")
sys.exit(1)
#resolve the name /Containers.dir/FactoryServerPy.object
try:
obj = rootContext.resolve(name)
-except CosNaming.NamingContext.NotFound, ex:
- print containerName , " not found in Naming Service"
+except CosNaming.NamingContext.NotFound as ex:
+ print(containerName , " not found in Naming Service")
sys.exit(1)
container = obj._narrow(Engines.Container)
-print container.getHostName()
+print(container.getHostName())
comp = container.load_impl("SalomeTestComponent","SalomeTestComponent")
-print comp._get_instanceName()
+print(comp._get_instanceName())
comp.ping()
comptest = comp._narrow(Engines.TestComponent)
if comptest is None:
- print "probleme cast"
-print comptest.Coucou(1)
+ print("probleme cast")
+print(comptest.Coucou(1))
# 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
salome_path = os.getenv("ROOT_SALOME", "")
salome_context_file = os.path.join(salome_path, "salome_context.cfg")
if not os.path.isfile(salome_context_file):
- print "File salome_context.cfg not found."
- print "Search path:" + salome_path
- print "This test needs ROOT_SALOME environment variable in order to run"
+ print("File salome_context.cfg not found.")
+ print("Search path:" + salome_path)
+ print("This test needs ROOT_SALOME environment variable in order to run")
exit(0)
config_appli_text = '''<application>
<module name="KERNEL" path="'''
kernel_path = os.getenv("KERNEL_ROOT_DIR", "")
if not os.path.isdir(kernel_path) :
- print "KERNEL_ROOT_DIR not defined"
+ print("KERNEL_ROOT_DIR not defined")
exit(0)
pass
self.salome_module = imp.load_source("SALOME", os.path.join(appli_dir, "salome"))
try:
self.salome_module.main(["start", "-t"])
- except SystemExit, e:
+ except SystemExit as e:
# There is an exit() call in salome.main. Just ignore it.
pass
ret = 0
try:
ret = self.salome_module.main(["shell", script])
- except SystemExit, e:
+ except SystemExit as e:
# return exit value
ret = e.code
return ret
def tearDown(self):
try:
self.salome_module.main(["killall"])
- except SystemExit, e:
+ except SystemExit as e:
pass
pass
pass #class TestEnvironment
Utils_ExceptHandlers.cxx
Utils_Mutex.cxx
)
- FILE(GLOB COMMON_HEADERS_HXX "${CMAKE_CURRENT_SOURCE_DIR}/*.hxx")
+ FILE(GLOB COMMON_HEADERS_HXX "${CMAKE_CURRENT_SOURCE_DIR}/*.hxx" )
ELSE()
TARGET_LINK_LIBRARIES(OpUtil ${COMMON_LIBS})
INSTALL(TARGETS OpUtil EXPORT ${PROJECT_NAME}TargetGroup DESTINATION ${SALOME_INSTALL_LIBS})
INSTALL(FILES ${COMMON_HEADERS_HXX} DESTINATION ${SALOME_INSTALL_HEADERS})
+INSTALL(FILES capsulethunk.h DESTINATION ${SALOME_INSTALL_HEADERS})
# 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
socket.gethostname() gives short or complete Hostname, depending on
defined aliases.
"""
- return string.split(socket.gethostname(),'.')[0]
+ hostname = socket.gethostname()
+ return hostname.split('.')[0]
class Identity:
def __init__(self,name):
--- /dev/null
+#ifndef __CAPSULETHUNK_H
+#define __CAPSULETHUNK_H
+
+#if ( (PY_VERSION_HEX < 0x02070000) \
+ || ((PY_VERSION_HEX >= 0x03000000) \
+ && (PY_VERSION_HEX < 0x03010000)) )
+
+#define __PyCapsule_GetField(capsule, field, default_value) \
+ ( PyCapsule_CheckExact(capsule) \
+ ? (((PyCObject *)capsule)->field) \
+ : (default_value) \
+ ) \
+
+#define __PyCapsule_SetField(capsule, field, value) \
+ ( PyCapsule_CheckExact(capsule) \
+ ? (((PyCObject *)capsule)->field = value), 1 \
+ : 0 \
+ ) \
+
+
+#define PyCapsule_Type PyCObject_Type
+
+#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
+#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))
+
+
+#define PyCapsule_New(pointer, name, destructor) \
+ (PyCObject_FromVoidPtr(pointer, destructor))
+
+
+#define PyCapsule_GetPointer(capsule, name) \
+ (PyCObject_AsVoidPtr(capsule))
+
+/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
+#define PyCapsule_SetPointer(capsule, pointer) \
+ __PyCapsule_SetField(capsule, cobject, pointer)
+
+
+#define PyCapsule_GetDestructor(capsule) \
+ __PyCapsule_GetField(capsule, destructor)
+
+#define PyCapsule_SetDestructor(capsule, dtor) \
+ __PyCapsule_SetField(capsule, destructor, dtor)
+
+
+/*
+ * Sorry, there's simply no place
+ * to store a Capsule "name" in a CObject.
+ */
+#define PyCapsule_GetName(capsule) NULL
+
+static int
+PyCapsule_SetName(PyObject *capsule, const char *unused)
+{
+ unused = unused;
+ PyErr_SetString(PyExc_NotImplementedError,
+ "can't use PyCapsule_SetName with CObjects");
+ return 1;
+}
+
+
+
+#define PyCapsule_GetContext(capsule) \
+ __PyCapsule_GetField(capsule, descr)
+
+#define PyCapsule_SetContext(capsule, context) \
+ __PyCapsule_SetField(capsule, descr, context)
+
+
+static void *
+PyCapsule_Import(const char *name, int no_block)
+{
+ PyObject *object = NULL;
+ void *return_value = NULL;
+ char *trace;
+ size_t name_length = (strlen(name) + 1) * sizeof(char);
+ char *name_dup = (char *)PyMem_MALLOC(name_length);
+
+ if (!name_dup) {
+ return NULL;
+ }
+
+ memcpy(name_dup, name, name_length);
+
+ trace = name_dup;
+ while (trace) {
+ char *dot = strchr(trace, '.');
+ if (dot) {
+ *dot++ = '\0';
+ }
+
+ if (object == NULL) {
+ if (no_block) {
+ object = PyImport_ImportModuleNoBlock(trace);
+ } else {
+ object = PyImport_ImportModule(trace);
+ if (!object) {
+ PyErr_Format(PyExc_ImportError,
+ "PyCapsule_Import could not "
+ "import module \"%s\"", trace);
+ }
+ }
+ } else {
+ PyObject *object2 = PyObject_GetAttrString(object, trace);
+ Py_DECREF(object);
+ object = object2;
+ }
+ if (!object) {
+ goto EXIT;
+ }
+
+ trace = dot;
+ }
+
+ if (PyCObject_Check(object)) {
+ PyCObject *cobject = (PyCObject *)object;
+ return_value = cobject->cobject;
+ } else {
+ PyErr_Format(PyExc_AttributeError,
+ "PyCapsule_Import \"%s\" is not valid",
+ name);
+ }
+
+EXIT:
+ Py_XDECREF(object);
+ if (name_dup) {
+ PyMem_FREE(name_dup);
+ }
+ return return_value;
+}
+
+#endif /* #if PY_VERSION_HEX < 0x02070000 */
+
+#endif /* __CAPSULETHUNK_H */