# ===============================================================
# These files are data, module or lib files
-INSTALL(FILES config_appli.xml salome.launch DESTINATION ${KERNEL_salomescript_DATA})
+#INSTALL(FILES salome.launch DESTINATION ${KERNEL_salomescript_DATA})
# These files are executable scripts
SET(SCRIPTS
appli_clean.sh
- appli_install.sh
- createAppli.sh
runIDLparser
- runNS.sh
- runSalome
- runSalome.csh
- runSalome.ksh
- runSalome.bat
- waitNS.sh
addToKillList.py
appli_gen.py
envSalome.py
killSalome.py
killSalomeWithPort.py
launchConfigureParser.py
- launchSalome.py
nameserver.py
NSparam.py
orbmodule.py
ORBConfigFile.py
- runNS.py
+ parseConfigFile.py
runSalome.py
+ runSession.py
+ runConsole.py
salomeConsole.py
+ salomeRunner.py
salome_session.py
salome_utils.py
searchFreePort.py
#
# These files are data, module or lib files
-dist_salomescript_DATA = \
- config_appli.xml \
- salome.launch
+dist_salomescript_DATA =
nodist_salomescript_DATA = \
VERSION
# These files are executable scripts
dist_salomescript_SCRIPTS = \
appli_clean.sh \
- appli_install.sh \
- createAppli.sh \
- runIDLparser \
- runNS.sh \
- runSalome \
- runSalome.csh \
- runSalome.ksh \
- runSalome.bat \
- waitNS.sh
+ runIDLparser
# These files are python files
dist_salomescript_PYTHON = \
killSalome.py \
killSalomeWithPort.py \
launchConfigureParser.py \
- launchSalome.py \
nameserver.py \
NSparam.py \
orbmodule.py \
ORBConfigFile.py \
- runNS.py \
+ parseConfigFile.py \
runSalome.py \
+ runSession.py \
+ runConsole.py \
salomeConsole.py \
+ salomeRunner.py \
salome_session.py \
salome_utils.py \
searchFreePort.py \
from salome_utils import getORBcfgInfo
my_version, my_host, my_port = getORBcfgInfo()
if info=='host':
- # keep print, stdout used in shell
- print my_host
os.environ['NSHOST']=my_host
return my_host
pass
elif info=='port':
- # keep print, stdout used in shell
- print my_port
os.environ['NSPORT']=my_port
return my_port
pass
else:
- # keep print, stdout used in shell
- print my_host, my_port
return my_host, my_port
pass
+#
# ------------------------------------------------------------------------
if __name__ == "__main__":
- if len(sys.argv) >1:
+ if len(sys.argv) >1:
if sys.argv[1]=='host':
- getNSparams('host')
+ my_host = getNSparams('host')
+ # keep print, stdout used in shell
+ print my_host
pass
elif sys.argv[1]=='port':
- getNSparams('port')
+ my_port = getNSparams('port')
+ # keep print, stdout used in shell
+ print my_port
pass
else:
- getNSparams()
+ my_host, my_port = getNSparams()
pass
pass
else:
getNSparams()
+ # keep print, stdout used in shell
+ print my_host, my_port
pass
pass
+#
for fn in ('envd',
'getAppliPath.py',
- 'searchFreePort.sh',
+ 'kill_remote_containers.py',
+# 'searchFreePort.sh', # REMOVED
+ 'runAppli', # OBSOLETE (replaced by salome.py)
+ 'runConsole', # OBSOLETE (replaced by salome.py)
'runRemote.sh',
- 'runAppli',
- 'runConsole',
- 'runSession',
'runSalomeScript',
- 'runTests',
+ 'runSession', # OBSOLETE (replaced by salome.py)
+# 'runTests', # REMOVED
+ 'salome.py',
'update_catalogs.py',
- 'kill_remote_containers.py',
'.bashrc',
):
virtual_salome.symlink("./bin/salome/appliskel/"+fn,os.path.join(home_dir, fn))
+++ /dev/null
-#!/bin/sh
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-SALOME_ROOT=${HOME}/SALOME2
-INSTALL_ROOT=${SALOME_ROOT}/Install
-
-APPLI_ROOT=`pwd`
-
-# --- clean appli
-rm -rf bin lib share doc envd getAppliPath.py searchFreePort.sh runAppli runConsole runSession env.d
-
-# --- install appli
-
-mkdir -p env.d
-ln -fs bin/salome/appliskel/envd .
-ln -fs bin/salome/appliskel/getAppliPath.py .
-ln -fs bin/salome/appliskel/searchFreePort.sh .
-ln -fs bin/salome/appliskel/runRemote.sh .
-ln -fs bin/salome/appliskel/runAppli .
-ln -fs bin/salome/appliskel/runConsole .
-ln -fs bin/salome/appliskel/runSession .
-ln -fs bin/salome/appliskel/runTests .
-ln -fs bin/salome/appliskel/.bashrc .
-
-# --- prerequisites
-
-if [ x${PREREQUISITE_SH} != x ]; then
- cp ${PREREQUISITE_SH} env.d/envProducts.sh;
-else
- # --- unless PREREQUISITE_SH defines the prerequisite script,
- # edit and uncomment the following line to set it, and comment the echo and exit lines
- #ln -fs myPathForSalomePrerequisiteScriptToBeSourced env.d/envProducts.sh
- echo "The file to source for SALOME prerequisite definition is not known:"
- echo "--> Edit the corresponding line in " $0 ",Comment this message and the following exit command,"
- exit 1;
-fi
-
-# --- symbolic links creation, from modules_root_dir
-
-VERSION=V3_2_0
-
-for module in KERNEL MED GUI GEOM SMESH VISU LIGHT NETGENPLUGIN PYCALCULATOR;
-do
- echo " ========= " ${module};
- python virtual_salome.py -v --prefix="." --module=$INSTALL_ROOT/${module}_${VERSION}
- echo "export ${module}_ROOT_DIR=$APPLI_ROOT" >> env.d/configSalome.sh
-done
-
-# --- HELLO module
-
-echo " ========= HELLO1";
-python virtual_salome.py -v --prefix="." --module=$INSTALL_ROOT/HELLO1_${VERSION}
-echo "export HELLO_ROOT_DIR=$APPLI_ROOT" >> env.d/configSalome.sh
-
-# --- PYHELLO module
-
-echo " ========= PYHELLO1";
-python virtual_salome.py -v --prefix="." --module=$INSTALL_ROOT/PYHELLO1_${VERSION}
-echo "export PYHELLO_ROOT_DIR=$APPLI_ROOT" >> env.d/configSalome.sh
-
-# --- GUI config
-
-echo "export config_var=$APPLI_ROOT:$APPLI_ROOT/share/salome/resources/gui" >> env.d/configGUI.sh
-
-# --- SAMPLES directory
-
-echo "export DATA_DIR=$INSTALL_ROOT/SAMPLES/${VERSION}/SAMPLES_SRC" >> env.d/configSalome.sh
-
-# ---
[ -z "$PS1" ] && return
# prefix prompt with naming server hostname and port
-export PS1='[NS='${NSHOST}':'${NSPORT}']'${PS1}
+#export PS1='[NS='${NSHOST}':'${NSPORT}']'${PS1}
+
+NO_COLOR="\[\033[0m\]"
+RED="\[\033[0;31m\]"
+DARK_RED="\[\033[1;31m\]"
+GREEN="\[\033[0;32m\]"
+DARK_GREEN="\[\033[1;32m\]"
+BROWN="\[\033[0;33m\]"
+DARK_BROWN="\[\033[1;33m\]"
+BLUE="\[\033[0;34m\]"
+DARK_BLUE="\[\033[1;34m\]"
+PURPLE="\[\033[0;35m\]"
+DARK_PURPLE="\[\033[1;35m\]"
+CYAN="\[\033[0;36m\]"
+DARK_CYAN="\[\033[1;36m\]"
+
+NS_COLOR=${BROWN}
+HOST_COLOR=${BLUE}
+PORT_COLOR=${PURPLE}
+DEFAULT_COLOR=${NO_COLOR}
+
+export PS1="${DEFAULT_COLOR}[${NS_COLOR}NS=${HOST_COLOR}${NSHOST}${NS_COLOR}:${PORT_COLOR}${NSPORT}${NS_COLOR}${DEFAULT_COLOR}]\$ "
# These files are executable scripts
SET(SCRIPTS
envd
- searchFreePort.sh
runRemote.sh
runAppli
runConsole
runSession
runSalomeScript
- runTests
.bashrc
getAppliPath.py
update_catalogs.py
kill_remote_containers.py
+ salome.py
)
SALOME_INSTALL_SCRIPTS("${SCRIPTS}" ${KERNEL_salomescript_SCRIPTS}/appliskel)
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-# -* Makefile *-
+# -* Makefile *-
# Author : Renaud Barate (EDF R&D)
# Module : KERNEL
# $Header$
# These files are executable scripts
dist_appliskel_SCRIPTS = \
envd \
- searchFreePort.sh \
runRemote.sh \
runAppli \
runConsole \
runSession \
runSalomeScript \
- runTests \
.bashrc
# These files are python files
dist_appliskel_PYTHON = \
getAppliPath.py \
update_catalogs.py \
- kill_remote_containers.py
+ kill_remote_containers.py \
+ salome.py
install-data-hook:
@for f in $(dist_appliskel_PYTHON) ; do \
import os
-def relpath(target, base):
- """ Find relative path from base to target
- if target== "/local/chris/appli" and base== "/local/chris" the result is appli
- if target== /tmp/appli and base /local/chris the result is ../../tmp/appli
- """
- target=target.split(os.path.sep)
- base=base.split(os.path.sep)
- for i in xrange(len(base)):
- if base[i] != target[i]:
- i=i-1
- #not in base
- break
- p=['..']*(len(base)-i-1)+target[i+1:]
- if p == []:
- return '.'
- return os.path.join( *p )
+def get_appli_path(filePath=None):
+ if filePath is None:
+ filePath = os.path.realpath(os.path.dirname(__file__))
-def set_var(VAR, strpath):
- """Set VAR environment variable """
- value = "%r" % strpath
- shell = os.getenv('SHELL')
- if shell and shell.endswith('csh'):
- return "setenv %s %s" % (VAR, value)
- else:
- return "export %s=%s" % (VAR, value)
+ homePath = os.path.realpath(os.getenv('HOME'))
+ applipath = os.path.relpath(filePath, homePath)
+ return applipath
if __name__ == "__main__":
- applipath=relpath(os.path.realpath(os.path.dirname(__file__)),os.path.realpath(os.getenv('HOME')))
- print applipath
+ applipath = get_appli_path()
+ print applipath
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
+
+echo "##############################################"
+echo "############### IMPORTANT NOTE ###############"
+echo "##############################################"
+echo "# The runAppli script is obsolete. #"
+echo "# Please consider the new salome.py command. #"
+echo "# More info: cedric.aguerre@edf.fr #"
+echo "##############################################"
+
+
APPLI_HOME=`dirname $0`
# --- retrieve APPLI path, relative to $HOME, set ${APPLI}
${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py $*
else
- ${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py
+ ${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py
fi
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
+
+echo "##############################################"
+echo "############### IMPORTANT NOTE ###############"
+echo "##############################################"
+echo "# The runConsole script is obsolete. #"
+echo "# Please consider the new salome.py command. #"
+echo "# More info: cedric.aguerre@edf.fr #"
+echo "##############################################"
+
+
APPLI_HOME=`dirname $0`
# --- retrieve APPLI path, relative to $HOME, set ${APPLI}
# Use it with args to run a program : runSession python -i myprog.py
# Use it without args to run an interactive shell under Salome env
+
+echo "##############################################"
+echo "############### IMPORTANT NOTE ###############"
+echo "##############################################"
+echo "# The runSession script is obsolete. #"
+echo "# Please consider the new salome.py command. #"
+echo "# More info: cedric.aguerre@edf.fr #"
+echo "##############################################"
+
+
+
APPLI_HOME=`dirname $0`
NSPORT=last
+++ /dev/null
-#!/bin/bash
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-# --- retrieve APPLI path, relative to $HOME, set ${APPLI}
-
-APPLI_HOME=`dirname $0`
-export APPLI=`${APPLI_HOME}/getAppliPath.py`
-
-# --- set the SALOME environment (prerequisites, MODULES_ROOT_DIR...)
-
-. ${HOME}/${APPLI}/envd ${HOME}/${APPLI}
-
-# --- if mpi lam, start lam (seems safe to be done several times)
-# arret manuel avec lamhalt
-
-if [ "$LAMBHOST" ]; then
- lamboot
-fi
-
-# --- invoque shell with or without args
-
-searchFreePort save test
-
-if [ $# -ne 0 ] ; then
- ${KERNEL_ROOT_DIR}/bin/salome/envSalome.py /bin/bash --rcfile ${HOME}/${APPLI}/.bashrc -c "$*"
-else
-
- ${KERNEL_ROOT_DIR}/bin/salome/envSalome.py /bin/bash --rcfile ${HOME}/${APPLI}/.bashrc
-fi
-
-rm ${OMNIORB_CONFIG}
-rm ${LAST_RUNNING_CONFIG}
--- /dev/null
+#! /usr/bin/env python
+
+import os
+import sys
+
+# Preliminary work to initialize path to SALOME Python modules
+def __initialize():
+ currentPath = os.path.dirname(__file__)
+ homePath = os.path.realpath(os.environ['HOME'])
+ appliPath = os.path.relpath(currentPath, homePath)
+ absoluteAppliPath = homePath+os.sep+appliPath
+ os.environ['APPLI'] = appliPath # needed to convert .sh environment files
+ os.environ['ABSOLUTE_APPLI_PATH'] = absoluteAppliPath
+
+ sys.path[:0] = [absoluteAppliPath+'/bin/salome']
+# End of preliminary work
+
+def __getConfigFileNamesDefault():
+ import glob
+
+ absoluteAppliPath = os.environ['ABSOLUTE_APPLI_PATH']
+ envdDir = absoluteAppliPath + '/env.d'
+ if os.path.isdir(envdDir):
+ configFileNames = glob.glob(envdDir+os.sep+'*.cfg') + glob.glob(envdDir+os.sep+'*.sh')
+ configFileNames = [os.path.basename(x) for x in configFileNames]
+ else:
+ configFileNames = []
+
+ configFileNames = [envdDir+'/'+x for x in configFileNames]
+ return configFileNames
+#
+
+def __getConfigFileNames(args):
+ # special case: configuration files are provided by user
+ # Search for command-line argument(s) --config=file1,file2,..., filen
+ configOptionPrefix = "--config="
+ configArgs = [ str(x) for x in args if str(x).startswith(configOptionPrefix) ]
+
+ if len(configArgs) == 0:
+ return __getConfigFileNamesDefault(), args
+
+ args = [ x for x in args if not x.startswith(configOptionPrefix) ]
+ files = [ x.replace(configOptionPrefix, '') for x in configArgs ]
+ configFileNames = []
+ for x in files:
+ configFileNames += x.split(',')
+
+ return configFileNames, args
+#
+
+if __name__ == "__main__":
+ args = sys.argv[1:]
+
+ # Identify application path then locate configuration files
+ __initialize()
+ configFileNames, args = __getConfigFileNames(args)
+
+ # Create a SalomeRunner which parses configFileNames to initialize environment
+ from salomeRunner import SalomeRunner
+ runner = SalomeRunner(configFileNames)
+
+
+ # Here set specific variables, if needed
+ # runner.addToPath('mypath')
+ # runner.addToLdLibraryPath('myldlibrarypath')
+ # runner.addToPythonPath('mypythonpath')
+ # runner.setEnviron('myvarname', 'value')
+
+
+ # Start SALOME, parsing command line arguments
+ runner.go(args)
+
+ print 'Thank you for using SALOME!'
+#
+++ /dev/null
-#!/bin/bash
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-# --- define port for CORBA naming service
-
-DEFAULT=default
-
-# call: searchFreePort [ save [test] ]
-searchFreePort() {
- # if not specified by optional first parameter, savemode is set to default
- savemode=${1:-$DEFAULT}
- # if not specified by optional second parameter, testmode is set to default
- testmode=${2:-$DEFAULT}
-
- echo -n "Searching for a free port for naming service: "
- export NSPORT=2810
- local limit=$NSPORT
- let limit=limit+100
-
- while [ 1 ]
- do
- aRes=`netstat -ltn | grep -E :${NSPORT}`
- if [ -z "$aRes" ]; then
- echo ${NSPORT} - Ok
- export NSPORT
- export NSHOST=`hostname`
-
- RETURN_VALUES=$(${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/ORBConfigFile.py ${HOME}/${APPLI}/USERS ${NSHOST} ${NSPORT} with_username=${USER})
- export OMNIORB_CONFIG=$(echo ${RETURN_VALUES} | cut -d' ' -f1)
-
- if [ "$savemode" = save ]
- then
- if [ "$testmode" = test ]
- then
- export LAST_RUNNING_CONFIG=${HOME}/${APPLI}/USERS/.omniORB_${USER}_${NSHOST}_test.cfg
- else
- export LAST_RUNNING_CONFIG=${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
- fi
-
- rm ${LAST_RUNNING_CONFIG}
- ln -s ${OMNIORB_CONFIG} ${LAST_RUNNING_CONFIG}
- fi
-
- break
- fi
- echo -n "${NSPORT} "
- if [[ $NSPORT -eq $limit ]] ; then
- echo
- echo "Can't find a free port to launch omniNames"
- echo "Try to kill the running servers and then launch SALOME again."
- exit
- fi
- let NSPORT=NSPORT+1
- done
-}
+++ /dev/null
-<application>
-<prerequisites path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/env_products.sh"/>
-<resources path="myCata.xml"/>
-<modules>
- <!-- variable name <MODULE>_ROOT_DIR is built with <MODULE> == name attribute value -->
- <!-- <MODULE>_ROOT_DIR values is set with path attribute value -->
- <!-- attribute gui (defaults = yes) indicates if the module has a gui interface -->
- <module name="KERNEL" gui="no" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/KERNEL_INSTALL"/>
- <module name="GUI" gui="no" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/GUI_4.1.1"/>
- <module name="MED" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/MED_4.1.1"/>
- <module name="GEOM" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/GEOM_4.1.1"/>
- <module name="SMESH" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/SMESH_4.1.1"/>
- <module name="YACS" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/YACS_4.1.1"/>
- <module name="VISU" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/VISU_4.1.1"/>
- <module name="HELLO" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/HELLO1_4.1.1"/>
- <module name="PYHELLO" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/PYHELLO1_4.1.1"/>
- <module name="NETGENPLUGIN" gui="no" path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/NETGENPLUGIN_4.1.1"/>
-</modules>
-<samples path="/data/tmplgls/secher/SALOME_V4.1.1_MD08/SAMPLES/4.1.1/SAMPLES_SRC"/>
-</application>
-
+++ /dev/null
-#!/bin/sh
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-comName=`which $0`
-rep=`dirname $comName`
-
-if [ $# -ne 1 ]; then
- echo "--- usage:"
- echo $0 AppliName
- echo "--- In which AppliName is a directory to create with SALOME application scripts"
-elif [ -d $1 ]; then
- echo $1 "directory already exists, nothing done"
-else
- mkdir -p $1
- mkdir -p $1/USERS
- cp -r $rep/appliskel/* $1
- cp $rep/appliskel/.bashrc $1
- chmod +x $1/*.sh $1/run* $1/envd
-fi
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
+
+##############################################
+############### IMPORTANT NOTE ###############
+##############################################
+# The envSalome.py script is obsolete. #
+# Please consider the new salome.py command. #
+# More info: cedric.aguerre@edf.fr #
+##############################################
+
+
import os
import sys
import setenv
# possible choices for the "embedded" and "standalone" parameters
embedded_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
-standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "pyContainer"]
+standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer"]
# values of boolean type (must be '0' or '1').
# xml_parser.boolValue() is used for correct setting
+++ /dev/null
-#! /usr/bin/env python
-# -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-import socket
-import os
-import sys
-import shutil
-
-#####################################################################
-def findFreePort(startPort, step) :
-
- currentPort = startPort;
- if step < 1:
- step = 1;
-
- serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
-
- portFound = 0;
- while (portFound != 1 and currentPort < 65536):
- try :
- serversocket.bind((socket.gethostname(), currentPort));
- portFound = 1;
- print str(currentPort) + ": " + "OK";
-# serversocket.shutdown(0);
-# serversocket.close();
- except Exception, inst:
- print str(currentPort) + ": " + str(inst.args);
- currentPort = currentPort+step;
-
-
-
-
- if (portFound != 1) :
- currentPort = -1;
- return currentPort;
-#####################################################################
-
-
-
-## 1. Generate config file for omniORB:
-# content:
-# InitRef = NameService=corbaname::[HOST_NAME]:[PORT_NUMBER]
-
-freePort = findFreePort(2810, 1);
-hostName = socket.gethostname();
-
-if (len(sys.argv) > 1) and sys.argv[1] == "-nothing" :
- print "port:" + str(freePort);
- sys.exit(0)
-
-if freePort < 0 :
- print
- print "Can't find a free port to launch omniNames"
- print "Try to kill the running servers and then launch SALOME again."
- print
- sys.exit(0)
-
-else :
- from ORBConfigFile import writeORBConfigFile
- writeORBConfigFile(os.environ.get('HOME'), hostName, freePort)
-
- if (len(sys.argv) > 1) and sys.argv[1] == "--save-config" :
- omniCfgCurrent = os.environ.get('HOME') + "/.omniORB_current.cfg";
- if os.name == "posix" :
- #make a symbolic link
- symlink(omniCfgFilePath, omniCfgCurrent);
- else :
- #copy the file
- shutil.copy(omniCfgFilePath, omniCfgCurrent);
-
- omniCfgFilePath = omniCfgCurrent;
-
-
- ## 2. Set the OMNIORB_CONFIG environment variable
- os.environ['OMNIORB_CONFIG']=omniCfgFilePath;
-
-
- ## 3. execute the file runSalome.py
- runSalomePyFilePath = os.environ.get('KERNEL_ROOT_DIR') + "/bin/salome/runSalome.py";
-
- if os.path.isfile(runSalomePyFilePath) :
- execfile(runSalomePyFilePath);
# Import the stubs for the Naming service
import CosNaming
-#from runNS import *
# -----------------------------------------------------------------------------
--- /dev/null
+import ConfigParser
+import os
+import logging
+import re
+from io import StringIO
+
+logging.basicConfig()
+logConfigParser = logging.getLogger(__name__)
+
+RESERVED_PREFIX = 'ADD_TO_'
+
+
+# :TRICKY: So ugly solution...
+class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
+ def __init__(self):
+ ConfigParser.SafeConfigParser.__init__(self)
+
+ # copied from python 2.6.8 Lib.ConfigParser.py
+ # modified (see code comments) to handle duplicate keys
+ def _read(self, fp, name):
+ """Parse a sectioned setup file.
+
+ The sections in setup file contains a title line at the top,
+ indicated by a name in square brackets (`[]'), plus key/value
+ options lines, indicated by `name: value' format lines.
+ Continuations are represented by an embedded newline then
+ leading whitespace. Blank lines, lines beginning with a '#',
+ and just about everything else are ignored.
+ """
+ cursect = None # None, or a dictionary
+ optname = None
+ lineno = 0
+ e = None # None, or an exception
+ while True:
+ line = fp.readline()
+ if not line:
+ break
+ lineno = lineno + 1
+ # comment or blank line?
+ if line.strip() == '' or line[0] in '#;':
+ continue
+ if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
+ # no leading whitespace
+ continue
+ # continuation line?
+ if line[0].isspace() and cursect is not None and optname:
+ value = line.strip()
+ if value:
+ cursect[optname].append(value)
+ # a section header or option header?
+ else:
+ # is it a section header?
+ mo = self.SECTCRE.match(line)
+ if mo:
+ sectname = mo.group('header')
+ if sectname in self._sections:
+ cursect = self._sections[sectname]
+ elif sectname == ConfigParser.DEFAULTSECT:
+ cursect = self._defaults
+ else:
+ cursect = self._dict()
+ cursect['__name__'] = sectname
+ self._sections[sectname] = cursect
+ # So sections can't start with a continuation line
+ optname = None
+ # no section header in the file?
+ elif cursect is None:
+ raise MissingSectionHeaderError(fpname, lineno, line)
+ # an option line?
+ else:
+ mo = self.OPTCRE.match(line)
+ if mo:
+ optname, vi, optval = mo.group('option', 'vi', 'value')
+ optname = self.optionxform(optname.rstrip())
+ # This check is fine because the OPTCRE cannot
+ # match if it would set optval to None
+ if optval is not None:
+ if vi in ('=', ':') and ';' in optval:
+ # ';' is a comment delimiter only if it follows
+ # a spacing character
+ pos = optval.find(';')
+ if pos != -1 and optval[pos-1].isspace():
+ optval = optval[:pos]
+ optval = optval.strip()
+ # allow empty values
+ if optval == '""':
+ optval = ''
+ # REPLACE following line (original):
+ #cursect[optname] = [optval]
+ # BY THESE LINES:
+ # Check if this optname already exists
+ if (optname in cursect) and (cursect[optname] is not None):
+ cursect[optname][0] += ','+optval
+ else:
+ cursect[optname] = [optval]
+ # END OF SUBSITUTION
+ else:
+ # valueless option handling
+ cursect[optname] = optval
+ else:
+ # a non-fatal parsing error occurred. set up the
+ # exception but keep going. the exception will be
+ # raised at the end of the file and will contain a
+ # list of all bogus lines
+ if not e:
+ e = ParsingError(fpname)
+ e.append(lineno, repr(line))
+ # if any parsing errors occurred, raise an exception
+ if e:
+ raise e
+
+ # join the multi-line values collected while reading
+ all_sections = [self._defaults]
+ all_sections.extend(self._sections.values())
+ for options in all_sections:
+ for name, val in options.items():
+ if isinstance(val, list):
+ options[name] = '\n'.join(val)
+ #
+
+
+# Parse configuration file
+# Input: filename, and a list of reserved keywords (environment variables)
+# Output: a list of pairs (variable, value), and a dictionary associating a list of user-defined values to each reserved keywords
+# Note: Does not support duplicate keys in a same section
+def parseConfigFile(filename, reserved = []):
+ config = MultiOptSafeConfigParser()
+ config.optionxform = str # case sensitive
+
+ # :TODO: test file existence
+
+ # Read config file
+ try:
+ config.read(filename)
+ except ConfigParser.MissingSectionHeaderError:
+ logConfigParser.error("No section found in file: %s"%(filename))
+ return []
+
+ return _processConfigFile(config, reserved)
+#
+
+def _processConfigFile(config, reserved = []):
+ # :TODO: may detect duplicated variables in the same section (raise a warning)
+ # or even duplicate sections
+
+ outputVariables = []
+ # Get raw items for each section, and make some processing for environment variables management
+ reservedKeys = [RESERVED_PREFIX+str(x) for x in reserved] # produce [ 'ADD_TO_reserved_1', 'ADD_TO_reserved_2', ..., ADD_TO_reserved_n ]
+ reservedValues = dict([str(i),[]] for i in reserved) # create a dictionary in which keys are the 'ADD_TO_reserved_i' and associated values are empty lists: { 'reserved_1':[], 'reserved_2':[], ..., reserved_n:[] }
+ sections = config.sections()
+ for section in sections:
+ entries = config.items(section, raw=False) # use interpolation
+ if len(entries) == 0: # empty section
+ logConfigParser.warning("Empty section: %s in file: %s"%(section, filename))
+ pass
+ for key,val in entries:
+ if key in reserved:
+ logConfigParser.error("Invalid use of reserved variable: %s in file: %s"%(key, filename))
+ else:
+ expandedVal = os.path.expandvars(val) # expand environment variables
+ # Search for not expanded variables (i.e. non-existing environment variables)
+ pattern = re.compile('\${ ( [^}]* ) }', re.VERBOSE) # string enclosed in ${ and }
+ expandedVal = pattern.sub(r'', expandedVal) # remove matching patterns
+ # Trim colons
+ expandedVal = _trimColons(expandedVal)
+
+ if key in reservedKeys:
+ shortKey = key[len(RESERVED_PREFIX):]
+ vals = expandedVal.split(',')
+ reservedValues[shortKey] += vals
+ # remove left&right spaces on each element
+ vals = [v.strip(' \t\n\r') for v in vals]
+ else:
+ outputVariables.append((key, expandedVal))
+ pass
+ pass # end if key
+ pass # end for key,val
+ pass # end for section
+
+ return outputVariables, reservedValues
+#
+
+def _trimColons(var):
+ v = var
+ # Remove leading and trailing colons (:)
+ pattern = re.compile('^:+ | :+$', re.VERBOSE)
+ v = pattern.sub(r'', v) # remove matching patterns
+ # Remove multiple colons
+ pattern = re.compile('::+', re.VERBOSE)
+ v = pattern.sub(r':', v) # remove matching patterns
+ return v
+#
+
+# This class is used to parse .sh environment file
+# It deals with specific treatments:
+# - virtually add a section to configuration file
+# - process shell keywords (if, then...)
+class EnvFileConverter(object):
+ def __init__(self, fp, section_name, reserved = [], outputFile=None):
+ self.fp = fp
+ self.sechead = '[' + section_name + ']\n'
+ self.reserved = reserved
+ self.outputFile = outputFile
+ self.allParsedVariableNames=[]
+ # exclude line that begin with:
+ self.exclude = [ 'if', 'then', 'fi', '#' ]
+ # discard the following keywords if at the beginning of line:
+ self.discard = [ 'export' ]
+
+ def readline(self):
+ if self.sechead:
+ try:
+ if self.outputFile is not None:
+ self.outputFile.write(self.sechead)
+ return self.sechead
+ finally:
+ self.sechead = None
+ else:
+ line = self.fp.readline()
+ # trim whitespaces
+ line = line.strip(' \t\n\r')
+ # line of interest? (not beginning by a keyword of self.exclude)
+ for k in self.exclude:
+ if line.startswith(k):
+ return '\n'
+ # look for substrinsg beginning with sharp charcter ('#')
+ line = re.sub(r'#.*$', r'', line)
+ # line to be pre-processed? (beginning by a keyword of self.discard)
+ for k in self.discard:
+ if line.startswith(k):
+ line = line[len(k):]
+ line = line.strip(' \t\n\r')
+ # process reserved keywords
+ for k in self.reserved:
+ if line.startswith(k) and "=" in line:
+ variable, value = line.split('=')
+ value = self._purgeValue(value, k)
+ line = RESERVED_PREFIX + k + ": " + value
+ # Update list of variable names
+ if "=" in line:
+ variable, value = line.split('=')
+ self.allParsedVariableNames.append(variable)
+ # Self-extending variables that are not in reserved keywords
+ # Example: FOO=something:${FOO}
+ # :TODO:
+ #
+ # replace "${FOO}" and "$FOO" and ${FOO} and $FOO by %(FOO)s if FOO is
+ # defined in current file (i.e. it is not an external environment variable)
+ for k in self.allParsedVariableNames:
+ key = r'\$\{?'+k+'\}?'
+ pattern = re.compile(key, re.VERBOSE)
+ line = pattern.sub(r'%('+k+')s', line)
+ # Remove quotes
+ pattern = re.compile(r'\"', re.VERBOSE)
+ line = pattern.sub(r'', line)
+ #
+ # Replace `shell_command` by its result
+ def myrep(obj):
+ obj = re.sub('`', r'', obj.group(0)) # remove quotes
+ import subprocess
+ res = subprocess.Popen([obj], stdout=subprocess.PIPE).communicate()[0]
+ res = res.strip(' \t\n\r') # trim whitespaces
+ return res
+ #
+ line = re.sub('`[^`]+`', myrep, line)
+ #
+ if self.outputFile is not None:
+ self.outputFile.write(line+'\n')
+ return line
+
+ def _purgeValue(self, value, name):
+ # Replace foo:${PATTERN}:bar or foo:$PATTERN:bar by foo:bar
+ key = r'\$\{?'+name+'\}?'
+ pattern = re.compile(key, re.VERBOSE)
+ value = pattern.sub(r'', value)
+
+ # trim colons
+ value = _trimColons(value)
+
+ return value
+ #
+
+# Convert .sh environment file to configuration file format
+def convertEnvFileToConfigFile(envFilename, configFilename):
+ #reserved=['PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH']
+ reserved=['PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'MANPATH', 'R_LIBS', 'PV_PLUGIN_PATH']
+ fileContents = open(envFilename, 'r').read()
+
+ pattern = re.compile('\n[\n]+', re.VERBOSE) # multiple '\n'
+ fileContents = pattern.sub(r'\n', fileContents) # replace by a single '\n'
+
+ finput = StringIO(unicode(fileContents))
+ foutput = open(configFilename, 'w')
+
+ config = MultiOptSafeConfigParser()
+ config.optionxform = str # case sensitive
+ config.readfp(EnvFileConverter(finput, 'SALOME Configuration', reserved, outputFile=foutput))
+ foutput.close()
+
+ logConfigParser.info('Configuration file generated: %s'%configFilename)
+#
--- /dev/null
+# -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2012 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.
+#
+# 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
+#
+
+def __prompt(vars = None, commands=[], message = "Connecting to SALOME"):
+ if vars is None:
+ vars = globals()
+ import code
+ import rlcompleter
+ import readline
+ readline.parse_and_bind("tab: complete")
+ # calling this with globals ensures we can see the environment
+ print message
+ shell = code.InteractiveConsole(vars)
+ for cmd in commands:
+ shell.push(cmd)
+ return shell.interact
+#
+
+def connect(args=[]):
+ p = __prompt(commands=["import salomeConsole"])
+ p()
+#
+++ /dev/null
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-#log files localization
-#
-import os, commands, sys, re, string, socket
-from Utils_Identity import getShortHostName
-
-if sys.platform == "win32":
- # temporarily using home directory for Namning Service logs
- # to be replaced with TEMP later...
- os.environ["BaseDir"]=os.environ["HOME"]
-else:
- os.environ["BaseDir"]="/tmp"
-
-os.environ["Username"]=os.environ["USER"]
-
-# kill OmniNames if exists
-
-#killall -q -9 omniNames
-
-# clear log files
-
-def startOmni():
- try:
- os.mkdir(os.environ["BaseDir"] + "/logs")
- os.chmod(os.environ["BaseDir"] + "/logs", 0777)
- except:
- #print "Can't create " + os.environ["BaseDir"] + "/logs"
- pass
-
- upath = os.environ["BaseDir"] + "/logs/" + os.environ["Username"]
-
- try:
- os.mkdir(upath)
- except:
- #print "Can't create " + upath
- pass
-
- #os.system("touch " + upath + "/dummy")
- for fname in os.listdir(upath):
- try:
- if not fname.startswith("."): os.remove(upath + "/" + fname)
- except:
- pass
- #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
-
- print "Name Service... "
- #hname=os.environ["HOST"] #commands.getoutput("hostname")
- if sys.platform == "win32":
- hname=getShortHostName()
- else:
- hname=socket.gethostname()
-
- print "hname=",hname
-
- f=open(os.environ["OMNIORB_CONFIG"])
- ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
- print "ss = ", ss
- f.close()
- aPort=re.findall("\d+", ss[0])[0]
-
- #aSedCommand="s/.*NameService=corbaname::" + hname + ":\([[:digit:]]*\)/\1/"
- #print "sed command = ", aSedCommand
- #aPort = commands.getoutput("sed -e\"" + aSedCommand + "\"" + os.environ["OMNIORB_CONFIG"])
- global process_id
- print "port=", aPort
- if sys.platform == "win32":
- #import win32pm
- #command = ['omniNames -start ' , aPort , ' -logdir ' , '\"' + upath + '\"']
- #os.system("start omniNames -start " + aPort + " -logdir " + "\"" + upath + "\"" )
- command = "start omniNames -start " + aPort + " -logdir " + "\"" + upath + "\""
- #print command
- pid = win32pm.spawnpid( string.join(command, " "), -nc )
- process_id[pid]=command
- else:
- os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
-
- print "ok"
- print "to list contexts and objects bound into the context with the specified name : showNS "
-
-# In LifeCycleCORBA, FactoryServer is started with rsh on the requested
-# computer if this Container does not exist. Default is localhost.
-# Others Containers are started with start_impl method of FactoryServer Container.
-# For using rsh it is necessary to have in the ${HOME} directory a .rhosts file
-# Warning : on RedHat the file /etc/hosts contains by default a line like :
-# 127.0.0.1 bordolex bordolex.paris1.matra-dtv.fr localhost.localdomain localhost
-# (bordolex is the station name). omniNames on bordolex will be accessible from other
-# computers only if the computer name is removed on that line like :
-# 127.0.0.1 bordolex.paris1.matra-dtv.fr localhost.localdomain localhost
-
-# To start dynamically Containers on several computers you need to
-# put in the ${OMNIORB_CONFIG} file a computer name instead of "localhost"
-# example : ORBInitRef NameService=corbaname::dm2s0017
-
-# If you need to use several omniNames running on the same computer, you have to :
-#1. put in your ${OMNIORB_CONFIG} file a computer name and port number
-# example : ORBInitRef NameService=corbaname::dm2s0017:1515
-#2. start omninames with this port number in runNS.sh
-# example : omniNames -start 1515 -logdir ${BaseDir}/logs/${Username} &
+++ /dev/null
-#!/bin/sh
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-#log files localization
-#
-BaseDir=/tmp
-Username=`/usr/bin/whoami`
-
-# kill OmniNames if exists
-
-#killall -q -9 omniNames
-
-# clear log files
-
-mkdir -m 777 ${BaseDir}/logs
-mkdir ${BaseDir}/logs/${Username}
-touch ${BaseDir}/logs/${Username}/dummy
-\rm -f ${BaseDir}/logs/${Username}/omninames* ${BaseDir}/logs/${Username}/dummy ${BaseDir}/logs/${Username}/*.log
-
-echo "Name Service... "
-aSedCommand="s/.*NameService=corbaname::`hostname`:\([[:digit:]]*\)/\1/"
-aPort=`cat $OMNIORB_CONFIG | grep NameService | sed -e"$aSedCommand"`
-omniNames -start $aPort -logdir ${BaseDir}/logs/${Username} &
-
-# In LifeCycleCORBA, FactoryServer is started with rsh on the requested
-# computer if this Container does not exist. Default is localhost.
-# Others Containers are started with start_impl method of FactoryServer Container.
-# For using rsh it is necessary to have in the ${HOME} directory a .rhosts file
-# Warning : on RedHat the file /etc/hosts contains by default a line like :
-# 127.0.0.1 bordolex bordolex.paris1.matra-dtv.fr localhost.localdomain localhost
-# (bordolex is the station name). omniNames on bordolex will be accessible from other
-# computers only if the computer name is removed on that line like :
-# 127.0.0.1 bordolex.paris1.matra-dtv.fr localhost.localdomain localhost
-
-# To start dynamically Containers on several computers you need to
-# put in the ${OMNIORB_CONFIG} file a computer name instead of "localhost"
-# example : ORBInitRef NameService=corbaname::dm2s0017
-
-# If you need to use several omniNames running on the same computer, you have to :
-#1. put in your ${OMNIORB_CONFIG} file a computer name and port number
-# example : ORBInitRef NameService=corbaname::dm2s0017:1515
-#2. start omninames with this port number in runNS.sh
-# example : omniNames -start 1515 -logdir ${BaseDir}/logs/${Username} &
-
-echo ok
-echo "to list contexts and objects bound int the context with the specified name : showNS "
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py $*
+
+echo "##############################################"
+echo "############### IMPORTANT NOTE ###############"
+echo "##############################################"
+echo "# The runSalome script is obsolete. #"
+echo "# Please consider the new salome.py command. #"
+echo "# More info: cedric.aguerre@edf.fr #"
+echo "##############################################"
+
+# **********************************************************
+# This file is used by m4 files in many modules to detect SALOME KERNEL.
+# Its initial purpose (starting salome) can be replaced by new salome.py command.
+# When definitively switching from autotools to Cmake, this file may be removed.
+# **********************************************************
+
+
+
+#${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py $*
+
+echo "The runSalome script is obsolete."
+echo "Please consider the new salome.py command."
+echo "More info: cedric.aguerre@edf.fr"
+
+
+
# -----------------------------------------------------------------------------
# examples:
# - parameters for launching are taken from SalomeApp.xml;
# - if the config file does not exist, it is created with default values.
#
-#
+#
# $: ${KERNEL_ROOT_DIR}/bin/salome/runSalome --modules=GEOM,SMESH,VISU,MED --embedded=registry,study,moduleCatalog,cppContainer --standalone=pyContainer --xterm --killall
#
# parameters from command line supersede those from SalomeApp.xml
# par defaut, les differents serveurs ouvrent des fenêtres xterm
# (cf. runSalome.py)
# le serveur Logger n'est pas obligatoire (commenté dans runSalome.py)
-#
+#
# -----------------------------------------------------------------------------
+++ /dev/null
-@REM Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
-@REM
-@REM Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-@REM CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
-@REM
-@REM This library is free software; you can redistribute it and/or
-@REM modify it under the terms of the GNU Lesser General Public
-@REM License as published by the Free Software Foundation; either
-@REM version 2.1 of the License.
-@REM
-@REM This library is distributed in the hope that it will be useful,
-@REM but WITHOUT ANY WARRANTY; without even the implied warranty of
-@REM MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-@REM Lesser General Public License for more details.
-@REM
-@REM You should have received a copy of the GNU Lesser General Public
-@REM License along with this library; if not, write to the Free Software
-@REM Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-@REM
-@REM See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-@REM
-
-@"%PYTHONBIN%" "%KERNEL_ROOT_DIR%\bin\salome\envSalome.py" "%PYTHONBIN%" "%KERNEL_ROOT_DIR%\bin\salome\runSalome.py" %*\r
+++ /dev/null
-#!/bin/csh -f
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-runSalome --gui --modules=GEOM,SMESH,VISU,MED --killall
+++ /dev/null
-#!/bin/ksh
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-searchFreePort
-
-if [[ "$*" = "-nothing" ]]; then
- echo "port:$NSPORT"
-elif [ $# -ne 0 ] ; then
- python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py $*
-else
- python ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py
-fi
-
-# -----------------------------------------------------------------------------
-# examples:
-# ---------
-# $: ${KERNEL_ROOT_DIR}/bin/salome/runSalome
-#
-# - parameters for launching are taken from SalomeApp.xml;
-# - if the config file does not exist, it is created with default values.
-#
-#
-# $: ${KERNEL_ROOT_DIR}/bin/salome/runSalome --modules=GEOM,SMESH,VISU,MED --embedded=registry,study,moduleCatalog,cppContainer --standalone=pyContainer --xterm --killall
-#
-# parameters from command line supersede those from SalomeApp.xml
-#
-# Some CORBA servers can be launched in the SALOME_Session_Server's process
-# (embedded = same process) or in a separate process (standalone):
-# --> registry,study,moduleCatalog,cppContainer
-# Other CORBA servers could only be launched in separate process (standalone):
-# --> pyContainer
-#
-# $: ${KERNEL_ROOT_DIR}/bin/salome/runSalome -h
-# help
-# -----------------------------------------------------------------------------
-#
-# l'option -i permet de garder l'interpreteur python ouvert :
-# par defaut, les differents serveurs ouvrent des fenêtres xterm
-# (cf. runSalome.py)
-# le serveur Logger n'est pas obligatoire (commenté dans runSalome.py)
-#
-# -----------------------------------------------------------------------------
-# Example on CCRT (without ihm) :
-# ${KERNEL_ROOT_DIR}/bin/salome/runSalome.py --terminal --modules=MED,CALCULATOR,COMPONENT --standalone=registry,study,moduleCatalog,cppContainer,pyContainer --killall
from launchConfigureParser import verbose
from server import process_id, Server
-if sys.platform == "win32":
- SEP = ";"
-else:
- SEP = ":"
-
# -----------------------------------------------------------------------------
from killSalome import killAllPorts
cata_path.append(cata_file)
modules_cata[module]=cata_file
- for path in os.getenv("SALOME_CATALOGS_PATH","").split(SEP):
+ for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
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]
# ---
-class ContainerPYServer(Server):
- def __init__(self,args):
- self.args=args
- self.initArgs()
- if sys.platform == "win32":
- self.CMD=[os.environ["PYTHONBIN"], '\"'+os.environ["KERNEL_ROOT_DIR"] + '/bin/salome/SALOME_ContainerPy.py'+'\"','FactoryServerPy']
- else:
- self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
-
-# ---
-
class LoggerServer(Server):
def __init__(self,args):
self.args=args
if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
self.SCMD2+=['CPP']
if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
- self.SCMD2+=['PY']
+ raise Exception('Python containers no longer supported')
if self.args['gui']:
session_gui = True
if self.args.has_key('session_gui'):
#
if 'pyContainer' in args['standalone']:
- myServer=ContainerPYServer(args)
- myServer.run()
- if sys.platform == "win32":
- clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
- else:
- clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
+ raise Exception('Python containers no longer supported')
#
# Wait until Session Server is registered in naming service
killMyPort(port)
pass
return
+#
-# -----------------------------------------------------------------------------
-
-if __name__ == "__main__":
+def runSalome():
import user
clt,args = main()
# --
pass
# --
pass
+#
+
+# -----------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ runSalome()
+#
--- /dev/null
+# -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2012 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.
+#
+# 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
+#
+
+import os
+import sys
+from optparse import OptionParser
+from NSparam import getNSparams
+
+# Use to display newlines (\n) in epilog
+class MyParser(OptionParser):
+ def format_epilog(self, formatter):
+ return self.epilog
+#
+
+def configureSession(args=[]):
+ usage = "Usage: %prog [options]"
+ epilog = """\nIf the command is not given a shell is opened.
+If PORT and MACHINE are not given, try to connect to the last active session on the local machine.
+If PORT and MACHINE are given, try to connect to the remote session associated with PORT on MACHINE.
+If MACHINE is not given, try to connect to the session associated to PORT on the local machine.
+If PORT is not given, try to connect to the remote session associated to port 2810 on MACHINE.\n\n"""
+ parser = MyParser(usage=usage, epilog=epilog)
+ parser.add_option("-p", "--port", metavar="<port>", default=0,
+ action="store", type="int", dest="port",
+ help="The port to connect to."
+ )
+ parser.add_option("-m", "--machine", metavar="<machine>", default=0,
+ action="store", type="int", dest="machine",
+ help="The machine to connect to."
+ )
+ try:
+ (options, args) = parser.parse_args(args)
+ except Exception, e:
+ print e
+ return
+
+ port = options.port
+ machine = options.machine
+
+ # :GLITCH: this code defines specific environment variables (OMNIORB_CONFIG, NSPORT,
+ # NSHOST) which are later used by other modules. Working, but not really "safe"...
+ if not port:
+ if not machine:
+ # neither MACHINE nor PORT are given
+ # --- set omniORB configuration to current session if any
+ absoluteAppliPath = os.environ['ABSOLUTE_APPLI_PATH']
+ fileOmniConfig = absoluteAppliPath + '/USERS/.omniORB_' + os.environ['USER'] + '_last.cfg'
+ if os.path.isfile(fileOmniConfig):
+ os.environ['OMNIORB_CONFIG'] = fileOmniConfig
+ # --- set environment variables for port and hostname of NamingService
+ host, port = getNSparams()
+ os.environ['NSHOST'] = host
+ os.environ['NSPORT'] = port
+ else:
+ # No running session
+ os.environ['NSHOST'] = "no_host"
+ os.environ['NSPORT'] = "no_port"
+ pass
+ else:
+ # only MACHINE is given
+ _writeConfigFile(2810, os.environ['NSHOST'])
+ #
+ else:
+ if not machine:
+ # only PORT is given
+ os.environ['NSHOST'] = `hostname`
+ pass
+ # both MACHINE and PORT are given
+ _writeConfigFile(os.environ['NSPORT'], os.environ['NSHOST'])
+ #
+#
+
+# --- set the OMNIORB_CONFIG file and environment relative to this run of SALOME
+def _writeConfigFile(port, host):
+ os.environ['NSPORT'] = port
+ os.environ['NSHOST'] = host
+
+ absoluteAppliPath = os.environ['ABSOLUTE_APPLI_PATH']
+ path = absoluteAppliPath + '/USERS'
+ kwargs = {'with_username' : os.environ['USER']}
+
+ from ORBConfigFile import writeORBConfigFile
+ [ filename, msgSize ] = writeORBConfigFile(path, host, port, kwargs)
+
+ os.environ['OMNIORB_CONFIG'] = filename
+#
+++ /dev/null
-<Configuration-list>
- <launchoptions>
- <gui>yes</gui>
- <logger>no</logger>
- <xterm>no</xterm>
- <portkill>yes</portkill>
- <killall>no</killall>
- </launchoptions>
- <modules-list>
- <module name="GEOM"/>
- <module name="SMESH">
- <plugin name="NETGENPlugin"/>
- <plugin name="GHS3DPlugin"/>
- </module>
- <module name="VISU"/>
- <module name="MED"/>
- <module name="COMPONENT"/>
- <module name="PYCALCULATOR"/>
- </modules-list>
- <embedded-list>
- <embeddedserver>registry</embeddedserver>
- <embeddedserver>study</embeddedserver>
- <embeddedserver>moduleCatalog</embeddedserver>
- <embeddedserver>cppContainer</embeddedserver>
- </embedded-list>
- <standalone-list>
- <standaloneserver>pyContainer</standaloneserver>
- </standalone-list>
-</Configuration-list>
else:
sys.exit(1)
-print sys.argv
+#print sys.argv
#direct adress from clt.orb.object_to_string(clt.rootContext)
#sys.argv=sys.argv+['-ORBInitRef','NameService=IOR:010000000100000000000000010000000000000023000000010100000a0000006c6f63616c686f737400fa0a0b0000004e616d6553657276696365']
--- /dev/null
+import os
+import sys
+import logging
+
+from parseConfigFile import parseConfigFile
+from parseConfigFile import convertEnvFileToConfigFile
+
+import tempfile
+import pickle
+import subprocess
+import platform
+
+"""
+The SalomeRunner class in an API to configure SALOME environment then
+start SALOME using a single python command.
+
+"""
+class SalomeRunner:
+ """
+ Initialize environment from a list of configuration files
+ identified by their names.
+ These files should be in appropriate (new .cfg) format.
+ However you can give old .sh environment files; in this case,
+ the SalomeRunner class will try to automatically convert them
+ to .cfg format before setting the environment.
+ """
+ def __init__(self, configFileNames=[]):
+ for filename in configFileNames:
+ basename, extension = os.path.splitext(filename)
+ if extension == ".cfg":
+ self.__setEnvironmentFromConfigFile(filename)
+ elif extension == ".sh":
+ temp = tempfile.NamedTemporaryFile(suffix='.cfg')
+ try:
+ convertEnvFileToConfigFile(filename, temp.name)
+ self.__setEnvironmentFromConfigFile(temp.name)
+ finally:
+ # Automatically cleans up the file
+ temp.close()
+ else:
+ self._getLogger().warning("Unrecognized extension for configuration file: %s", filename)
+ #
+
+ def go(self, args):
+ # Run this module as a script, in order to use appropriate Python interpreter
+ # according to current path (initialized from environment files).
+ absoluteAppliPath = os.environ['ABSOLUTE_APPLI_PATH']
+ proc = subprocess.Popen(['python', absoluteAppliPath+'/bin/salome/salomeRunner.py', pickle.dumps(self), pickle.dumps(args)], shell=False, close_fds=True)
+ proc.wait()
+ #
+
+ """Append value to PATH environment variable"""
+ def addToPath(self, value):
+ self.__addToReserved( 'PATH', value)
+ #
+
+ """Append value to LD_LIBRARY_PATH environment variable"""
+ def addToLdLibraryPath(self, value):
+ self.__addToReserved('LD_LIBRARY_PATH', value)
+ #
+
+ """Append value to PYTHONPATH environment variable"""
+ def addToPythonPath(self, value):
+ self.__addToReserved('PYTHONPATH', value)
+ #
+
+ """Set environment variable to value"""
+ def setEnviron(self, name, value, overwrite=False):
+ env = os.getenv(name, '')
+ if env and not overwrite:
+ self._getLogger().warning("Environment variable already existing and not overwritten: %s", name)
+ return
+
+ if env:
+ self._getLogger().info("Overwriting environment variable: %s", name)
+
+ value = os.path.expandvars(value) # expand environment variables
+ self._getLogger().debug("Set environment variable: %s=%s", name, value)
+ os.environ[name] = value
+ #
+
+ ###################################
+ # This begins the private section #
+ ###################################
+
+ def _usage(self, unused=[]):
+ exeName = os.path.splitext(os.path.basename(__file__))[0]
+
+ msg = '''\
+Usage: %s [command] [options] [--config=file1,...,filen]
+
+Commands:
+ start Launches SALOME virtual application [DEFAULT]
+ shell Executes a script under SALOME application environment
+ connect Connects a Python console to the active SALOME session
+ killall Kill all SALOME running sessions
+ info Display some information about SALOME
+ help Show this message
+ coffee Yes! SALOME can also make coffee!!"\
+
+'''%exeName
+
+ print msg
+ #
+
+ def __parseArguments(self, args):
+ if len(args) == 0 or args[0].startswith("-"):
+ return None, args
+
+ command = args[0]
+ options = args[1:]
+
+ availableCommands = {
+ 'start' : '_runAppli',
+ 'shell' : '_runSession',
+ 'connect' : '_runConsole',
+ 'killall': '_killAll',
+ 'info': '_showInfo',
+ 'help': '_usage',
+ 'coffee' : '_makeCoffee'
+ }
+
+ if not command in availableCommands.keys():
+ self._getLogger().error("Unrecognized command: %s.", command)
+ self._usage()
+ sys.exit(1)
+
+ return availableCommands[command], options
+ #
+
+ """
+ Run SALOME!
+ Args consist in a mandatory command followed by optionnal parameters.
+ See usage for details on commands.
+ """
+ def _getStarted(self, args):
+ command, options = self.__parseArguments(args)
+ sys.argv = options
+
+ if command is None:
+ if args and args[0] in ["-h","--help","help"]:
+ self._usage()
+ sys.exit(0)
+ # try to default to "start" command
+ command = "_runAppli"
+
+ try:
+ getattr(self, command)(options) # run appropriate method
+ except AttributeError:
+ self._getLogger().error("Method %s is not implemented.", command)
+ sys.exit(1)
+ #
+
+ def __setEnvironmentFromConfigFile(self, filename):
+ configVars, reservedDict = parseConfigFile(filename, reserved=['PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH'])
+
+ # set environment
+ for reserved in reservedDict:
+ a = filter(None, reservedDict[reserved]) # remove empty elements
+ reformattedVals = ':'.join(a)
+ self.__addToReserved(reserved, reformattedVals)
+ pass
+
+ for key,val in configVars:
+ self.setEnviron(key, val, overwrite=True)
+ pass
+
+ sys.path[:0] = os.environ['PYTHONPATH'].split(':')
+ #
+
+ def __addToReserved(self, name, value):
+ if value == '':
+ return
+
+ value = os.path.expandvars(value) # expand environment variables
+ self._getLogger().debug("Add to %s: %s", name, value)
+ env = os.getenv(name, None)
+ if env is None:
+ os.environ[name] = value
+ else:
+ os.environ[name] = value + os.pathsep + env
+ #
+
+ def _runAppli(self, args=[]):
+ # Initialize SALOME environment
+ sys.argv = ['runSalome'] + args
+ import setenv
+ setenv.main(True)
+
+ import runSalome
+ runSalome.runSalome()
+ #
+
+ def _runSession(self, args=[]):
+ sys.argv = ['runSession'] + args
+ import runSession
+ runSession.configureSession(args)
+
+ import setenv
+ setenv.main(True)
+
+ if args:
+ exe = args[0]
+ # if exe does not contain any slashes (/), search in PATH
+ # if exe contains slashes:
+ # if exe begins with a slash, use this absolute path
+ # else build absolute path relative to current working directory
+ if (os.sep in exe) and (exe[0] is not os.sep):
+ args[0] = os.getcwd() + os.sep + exe
+
+ proc = subprocess.Popen(args, shell=False, close_fds=True)
+ proc.wait()
+ else:
+ absoluteAppliPath = os.environ['ABSOLUTE_APPLI_PATH']
+ cmd = ["/bin/bash", "--rcfile", absoluteAppliPath + "/.bashrc" ]
+ proc = subprocess.Popen(cmd, shell=False, close_fds=True)
+ proc.wait()
+ #
+
+ def _runConsole(self, args=[]):
+ # Initialize SALOME environment
+ sys.argv = ['runConsole'] + args
+ import setenv
+ setenv.main(True)
+
+ import runConsole
+ runConsole.connect()
+ #
+
+ def _killAll(self, args=[]):
+ #self._runAppli(['-k'] + args)
+ from killSalome import killAllPorts
+ killAllPorts()
+ #
+
+ def _showInfo(self, args=[]):
+ print "Running with python", platform.python_version()
+ self._runAppli(["--version"])
+ #
+
+ def _makeCoffee(self, args=[]):
+ print " ("
+ print " ) ("
+ print " ___...(-------)-....___"
+ print " .-\"\" ) ( \"\"-."
+ print " .-\'``\'|-._ ) _.-|"
+ print " / .--.| `\"\"---...........---\"\"` |"
+ print " / / | |"
+ print " | | | |"
+ print " \\ \\ | |"
+ print " `\\ `\\ | |"
+ print " `\\ `| |"
+ print " _/ /\\ /"
+ print " (__/ \\ /"
+ print " _..---\"\"` \\ /`\"\"---.._"
+ print " .-\' \\ / \'-."
+ print " : `-.__ __.-\' :"
+ print " : ) \"\"---...---\"\" ( :"
+ print " \'._ `\"--...___...--\"` _.\'"
+ print " \\\"\"--..__ __..--\"\"/"
+ print " \'._ \"\"\"----.....______.....----\"\"\" _.\'"
+ print " `\"\"--..,,_____ _____,,..--\"\"`"
+ print " `\"\"\"----\"\"\"`"
+ sys.exit(0)
+ #
+
+ # Add the following two methods since logger is not pickable
+ # Ref: http://stackoverflow.com/questions/2999638/how-to-stop-attributes-from-being-pickled-in-python
+ def __getstate__(self):
+ d = dict(self.__dict__)
+ del d['_logger']
+ return d
+ #
+ def __setstate__(self, d):
+ self.__dict__.update(d) # I *think* this is a safe way to do it
+ #
+ # Excluding self._logger from pickle operation imply using the following method to access logger
+ def _getLogger(self):
+ if not hasattr(self, '_logger'):
+ self._logger = logging.getLogger(__name__)
+ #self._logger.setLevel(logging.DEBUG)
+ return self._logger;
+ #
+
+###
+import pickle
+if __name__ == "__main__":
+ if len(sys.argv) == 3:
+ runner = pickle.loads(sys.argv[1])
+ args = pickle.loads(sys.argv[2])
+ runner._getStarted(args)
+ else:
+ SalomeRunner()._usage()
+#
+++ /dev/null
-#! /bin/sh
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-status=1
-while [ $status -ne 0 ]; do
- ls $HOME/$APPLI/USERS/.omniORB_${USER}_last.cfg 2> /dev/null
- status=$?
- sleep 1
- echo -n "#"
-done
-./runSession waitNS.py
-------------------------------------------------------------------------------
In a SALOME application, distributed components, servers and clients use
-the CORBA middleware for comunication. CORBA interfaces are defined via idl
+the CORBA middleware for communication. CORBA interfaces are defined via idl
files. All the different CORBA interfaces are available for users in Python,
see CORBA interfaces below.
For some general purpose services, CORBA interfaces have been encapsulated
in order to provide a simple interface (encapsulation is generally done in
-C++ classes, and a Python SWIG interface is also generated from C++, to
+C++ classes, and a Python SWIG interface is also generated from C++, to
ensure a consistent behavior between C++ modules and Python modules or user
script).
do it several times, so it is preferable to add these instructions
systematically in your scripts, to allow them to work in all configurations.
-Container and component instanciation
+Container and component instantiation
-------------------------------------
See LifeCycleCORBA_ for the C++ interface (Python interface obtained with SWIG
import salome
salome.salome_init()
-
+
import LifeCycleCORBA
lcc = LifeCycleCORBA.LifeCycleCORBA()
obj=lcc.FindOrLoad_Component("FactoryServer","SalomeTestComponent")
-
+
import Engines
comp=obj._narrow(Engines.TestComponent)
-
+
comp.Coucou(1)
The answer is something like::
'TestComponent_i : L = 1'
-
-The _narrow() instruction is not always mandatory in Python, but sometimes
+
+The _narrow() instruction is not always mandatory in Python, but sometimes
useful to be sure you have got the right type of object. Here, Testcomponent_
interface is defined in CORBA module Engines. With this example, it works also
without the _narrow() instruction::
A SALOME application is defined by a set of modules (GEOM, SMESH, ASTER...).
A SALOME User can define several SALOME Applications. These applications are
-runnable from the same user account. These applications may share the same
+runnable from the same user account. These applications may share the same
KERNEL and modules. Thus, the application configuration is independant of
KERNEL and must not be put in KERNEL_ROOT_DIR.
''''''''''''''''''''''''''''''''''''''''''''''''''''''
The script createAppli.sh in ${KERNEL_ROOT_DIR}/bin/salome creates an
-application directory with the given path in parameter. ${APPLI} is a path
+application directory with the given path in parameter. ${APPLI} is a path
relative to ${HOME}.
The directory is only a skeleton, the user has to edit several files to
(bin, lib, doc, share...), with, for each file (executable, script, data,
library, resources...), symbolic links to the actual file.
-Providing an existing an existing script for SALOME prerequisites (the same one
+Providing an existing script for SALOME prerequisites (the same one
used for modules compilation, or given with the modules installation), the
installation works without further modification for a single computer (unless
some modules needs a special environment not defined in the above script).
The ${APPLI} directory contains scripts for environment and runs. Environment
scripts must be configured (by the user) on each computer. All the environment
-scripts are in the ${APPLI}/env.d directory.
+scripts are in the ${APPLI}/env.d directory.
The script ${APPLI}/envd sources **all** the files (\*.sh) in ${APPLI}/env.d
in alphanumeric order (after edition, think to remove backup files). the envd
export SalomeAppConfig=${HOME}/${APPLI}
- where SalomeAppConfig designates the directory containing SalomeApp.xml.
- Note that ${APPLI} is already defined by the calling scripts when
+ where SalomeAppConfig designates the directory containing SalomeApp.xml.
+ Note that ${APPLI} is already defined by the calling scripts when
env.d/envSalome.sh is sourced.
User run scripts
It's often easier to develop and try Python scripts outside the GUI embedded
Python interpreter. Imagine, for instance, you are writing a script involving
geometry and mesh modules.
-first, launch a SALOME session with gui, then, on another terminal::
+First, launch a SALOME session with gui, then, on another terminal::
./runSession
python
SALOME_Application
INSTALL
kernel_resources
+ KERNEL_Services
userguide"
STYLESHEET=rst.css
Container
definition of a container
-
+
General concepts
================
- personalisation des procédures de construction
Developer' guide - integration tools
-====================================
-- Guide de l'intégrateur (développeur de nouveaux modules)
-(on lui montre ici le principe de construction et les ressources à
-disposition pour faire le travail)
+====================================
+- Guide de l'intégrateur (développeur de nouveaux modules) : (on lui montre ici le principe de construction et les ressources à disposition pour faire le travail)
- création d'un modules
- intégration code boîte noire (perfect, solver)
- - intégration bibliothèque de fonctions (hxx2salome, voir avec
- N.Crouzet)
- - intégration de modèles de données (xdata)
+ - intégration bibliothèque de fonctions (hxx2salome, voir avec N.Crouzet)
+ - intégration de modèles de données (xdata)
End user's guide
================
- Guide de l'utilisateur
- concept d'application (renvoie doc Paul)
- - commandes avancées (showNS, exemple de contact de la
- session, d'un engine, utilisation du lifeCycle, du module salome,
- des modules geompy et smesh)
+ - commandes avancées (showNS, exemple de contact de la session, d'un engine, utilisation du lifeCycle, du module salome, des modules geompy et smesh)
- utilisation en mode distribué (doc de B. Sechet)
- GUI and TUI documentation
RST Exemples
============
-See INSTALL_ for general information on required configuration and
+See INSTALL_ for general information on required configuration and
prerequisites, compilation procedure, setting environment principles.
.. _INSTALL: ./INSTALL.html
SALOME_ComponentPy.py
SALOME_PyNode.py
SALOME_Container.py
- SALOME_ContainerPy.py
)
ADD_DEFINITIONS(${HDF5_DEFINITIONS} ${LIBXML2_DEFINITIONS} ${OMNIORB_DEFINITIONS})
# Header to be installed
# ===============================================================
#
-# header files
+# header files
salomeinclude_HEADERS = \
SALOME_Component_i.hxx \
SALOME_Container_i.hxx \
SALOME_Container.py
# These files are executable scripts
-dist_salomescript_SCRIPTS=\
- SALOME_ContainerPy.py
+dist_salomescript_SCRIPTS=
#
# ===============================================================
@CORBA_LIBS@ \
$(PYTHON_LIBS)
-if WITH_MPI_SEQ_CONTAINER
+if WITH_MPI_SEQ_CONTAINER
COMMON_CPPFLAGS += @MPI_INCLUDES@
COMMON_LIBS += @MPI_LIBS@
endif
$(CORBA_LIBS) \
$(PYTHON_LIBS)
-if WITH_MPI_SEQ_CONTAINER
+if WITH_MPI_SEQ_CONTAINER
SALOME_Container_LDADD += $(MPI_LIBS)
endif
+++ /dev/null
-# -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2013 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.
-#
-# 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
-#
-
-# ================================================================================
-# WARNING: this file is deprecated and should not be used any more. It has been
-# replaced by the file __init__.py of the python package named "salome".
-# To prevent any error, a warning is raised in the case where this file is imported
-raise RuntimeError("WRN - the file salome.py is deprecated. It should NOT be used any more.")
-# ================================================================================
-
-
-# File : salome.py
-# Author : Paul RASCLE, EDF
-# Module : SALOME
-# $Header$
-#
-"""
-Module salome gives access to Salome ressources.
-
-variables:
-
- - salome.orb : CORBA
- - salome.naming_service : instance of naming Service class
- - methods:
- - Resolve(name) : find a CORBA object (ior) by its pathname
- - Register(name) : register a CORBA object under a pathname
-
- - salome.lcc : instance of lifeCycleCORBA class
- - methods:
- - FindOrLoadComponent(server,name) :
- obtain an Engine (CORBA object)
- or launch the Engine if not found,
- with a Server name and an Engine name
-
- - salome.sg : salome object to communicate with the graphical user interface (if any)
- - methods:
- - updateObjBrowser(bool):
- - getActiveStudyId():
- - getActiveStudyName():
-
- - SelectedCount(): returns number of selected objects
- - getSelected(i): returns entry of selected object number i
- - getAllSelected(): returns list of entry of selected objects
- - AddIObject(Entry): select an existing Interactive object
- - RemoveIObject(Entry): remove object from selection
- - ClearIObjects(): clear selection
-
- - Display(*Entry):
- - DisplayOnly(Entry):
- - Erase(Entry):
- - DisplayAll():
- - EraseAll():
-
- - IDToObject(Entry): returns CORBA reference from entry
-
- - salome.myStudyName : active Study Name
- - salome.myStudyId : active Study Id
- - salome.myStudy : the active Study itself (CORBA ior)
- - methods : defined in SALOMEDS.idl
-
-"""
-## @package salome
-# Module salome gives access to Salome ressources.
-#
-# \param salome.orb : CORBA orb object
-# \param salome.naming_service : instance of naming Service class (SALOME_NamingServicePy::SALOME_NamingServicePy_i)
-# \param salome.lcc : instance of lifeCycleCORBA class (SALOME_LifeCycleCORBA)
-# \param salome.sg : Salome object to communicate with the graphical user interface, if running (see interface in salome_iapp::SalomeOutsideGUI)
-# \param salome.myStudyName : active Study Name
-# \param salome.myStudyId : active Study Id
-# \param salome.myStudy : the active Study (interface SALOMEDS::Study)
-
-#
-from salome_kernel import *
-from salome_study import *
-from salome_iapp import *
-
-
-#
-# The next block is workaround for the problem of shared symbols loading for the extension modules (e.g. SWIG-generated)
-# that causes RTTI unavailable in some cases. To solve this problem, sys.setdlopenflags() function is used.
-# Depending on the Python version and platform, the dlopen flags can be defined in the dl, DLFUN or ctypes module.
-#
-import sys
-flags = None
-if not flags:
- try:
- # dl module can be unavailable
- import dl
- flags = dl.RTLD_NOW | dl.RTLD_GLOBAL
- except:
- pass
- pass
-if not flags:
- try:
- # DLFCN module can be unavailable
- import DLFCN
- flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL
- except:
- pass
- pass
-if not flags:
- try:
- # ctypes module can be unavailable
- import ctypes
- flags = ctypes.RTLD_GLOBAL
- except:
- pass
- pass
-
-if flags:
- sys.setdlopenflags(flags)
- pass
-
-orb, lcc, naming_service, cm,sg=None,None,None,None,None
-myStudyManager, myStudyId, myStudy, myStudyName=None,None,None,None
-
-salome_initial=1
-def salome_init(theStudyId=0,embedded=0):
- """
- Performs only once SALOME general purpose intialisation for scripts.
- optional argument : theStudyId
- When in embedded interpreter inside IAPP, theStudyId is not used
- When used without GUI (external interpreter)
- 0 : create a new study (default).
- n (>0) : try connection to study with Id = n, or create a new one
- if study not found.
- If study creation, its Id may be different from theStudyId !
- Provides:
- orb reference to CORBA
- lcc a LifeCycleCorba instance
- naming_service a naming service instance
- cm reference to the container manager
- sg access to SALOME GUI (when linked with IAPP GUI)
- myStudyManager the study manager
- myStudyId active study identifier
- myStudy active study itself (CORBA reference)
- myStudyName active study name
- """
- global salome_initial
- global orb, lcc, naming_service, cm
- global sg
- global myStudyManager, myStudyId, myStudy, myStudyName
-
- try:
- if salome_initial:
- salome_initial=0
- sg = salome_iapp_init(embedded)
- orb, lcc, naming_service, cm = salome_kernel_init()
- myStudyManager, myStudyId, myStudy, myStudyName =salome_study_init(theStudyId)
- pass
- pass
- except RuntimeError, inst:
- # wait a little to avoid trace mix
- import time
- time.sleep(0.2)
- x = inst
- 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
-
-#to expose all objects to pydoc
-__all__=dir()
#include "SALOMEDS.hxx"
#include <stdlib.h>
-SALOMEDS_Driver_i::SALOMEDS_Driver_i(Engines::EngineComponent_ptr theEngine, CORBA::ORB_ptr theORB)
+SALOMEDS_Driver_i::SALOMEDS_Driver_i(Engines::EngineComponent_ptr theEngine, CORBA::ORB_ptr theORB)
{
// engine should not be null - component is supposed to be inherited from Engines::EngineComponent
_engine = Engines::EngineComponent::_duplicate(theEngine);
// driver can be null - if component interface does not inherit SALOMEDS::Driver
_driver = SALOMEDS::Driver::_narrow(theEngine);
- _orb = CORBA::ORB::_duplicate(theORB);
+ _orb = CORBA::ORB::_duplicate(theORB);
}
SALOMEDS_Driver_i::SALOMEDS_Driver_i(SALOMEDS::Driver_ptr theDriver, CORBA::ORB_ptr theORB)
_driver = SALOMEDS::Driver::_duplicate(theDriver);
// engine can be null - since it is narrowed from SALOMEDS::Driver ptr which can be null
_engine = Engines::EngineComponent::_narrow(theDriver);
- _orb = CORBA::ORB::_duplicate(theORB);
+ _orb = CORBA::ORB::_duplicate(theORB);
}
SALOMEDS_Driver_i::~SALOMEDS_Driver_i()
{
}
-std::string SALOMEDS_Driver_i::GetIOR()
+std::string SALOMEDS_Driver_i::GetIOR()
{
std::string ior = "";
if ( !CORBA::is_nil(_engine) ) {
const std::string& theURL,
long& theStreamLength,
bool isMultiFile)
-{
+{
SALOMEDS::SComponent_var sco = SALOMEDS_SComponent_i::New (theComponent, _orb);
CORBA::String_var url = CORBA::string_dup(theURL.c_str());
return aTMPFile;
}
-
+
bool SALOMEDS_Driver_i::Load(const SALOMEDSImpl_SComponent& theComponent,
const unsigned char* theStream,
const long theStreamLength,
CORBA::Octet* anOctetBuf = (CORBA::Octet*)theStream;
SALOMEDS::TMPFile_var aStream;
- if (theStreamLength > 0)
- aStream = new SALOMEDS::TMPFile(theStreamLength, theStreamLength, anOctetBuf, 0);
- else
+ if (theStreamLength > 0)
+ aStream = new SALOMEDS::TMPFile(theStreamLength, theStreamLength, anOctetBuf, 0);
+ else
aStream = new SALOMEDS::TMPFile(0);
SALOMEDS::unlock();
CORBA::Octet* anOctetBuf = (CORBA::Octet*)theStream;
SALOMEDS::TMPFile_var aStream;
- if(theStreamLength > 0)
- aStream = new SALOMEDS::TMPFile(theStreamLength, theStreamLength, anOctetBuf, 0);
- else
+ if(theStreamLength > 0)
+ aStream = new SALOMEDS::TMPFile(theStreamLength, theStreamLength, anOctetBuf, 0);
+ else
aStream = new SALOMEDS::TMPFile(0);
SALOMEDS::unlock();
SALOMEDS::lock();
}
-std::string SALOMEDS_Driver_i::ComponentDataType()
+std::string SALOMEDS_Driver_i::ComponentDataType()
{
std::string dtype = "";
if ( !CORBA::is_nil(_driver) ) {
}
-SALOMEDSImpl_TMPFile* SALOMEDS_Driver_i::CopyFrom(const SALOMEDSImpl_SObject& theObject,
+SALOMEDSImpl_TMPFile* SALOMEDS_Driver_i::CopyFrom(const SALOMEDSImpl_SObject& theObject,
int& theObjectID,
long& theStreamLength)
{
CORBA::Octet* anOctetBuf = (CORBA::Octet*)theStream;
SALOMEDS::TMPFile_var aStream;
- if(theStreamLength > 0)
- aStream = new SALOMEDS::TMPFile(theStreamLength, theStreamLength, anOctetBuf, 0);
- else
+ if(theStreamLength > 0)
+ aStream = new SALOMEDS::TMPFile(theStreamLength, theStreamLength, anOctetBuf, 0);
+ else
aStream = new SALOMEDS::TMPFile(0);
SALOMEDS::unlock();
return entry;
}
-SALOMEDSImpl_TMPFile* SALOMEDS_Driver_i::DumpPython(SALOMEDSImpl_Study* theStudy,
- bool isPublished,
+SALOMEDSImpl_TMPFile* SALOMEDS_Driver_i::DumpPython(SALOMEDSImpl_Study* theStudy,
+ bool isPublished,
bool isMultiFile,
bool& isValidScript,
long& theStreamLength)
// SALOMEDS_DriverFactory
//###############################################################################################################
-SALOMEDS_DriverFactory_i::SALOMEDS_DriverFactory_i(CORBA::ORB_ptr theORB)
+SALOMEDS_DriverFactory_i::SALOMEDS_DriverFactory_i(CORBA::ORB_ptr theORB)
{
_orb = CORBA::ORB::_duplicate(theORB);
_name_service = new SALOME_NamingService(_orb);
}
-SALOMEDS_DriverFactory_i::~SALOMEDS_DriverFactory_i()
+SALOMEDS_DriverFactory_i::~SALOMEDS_DriverFactory_i()
{
delete _name_service;
}
SALOMEDS::lock();
if (CORBA::is_nil(obj)) {
- obj = SALOME_LifeCycleCORBA(_name_service).FindOrLoad_Component("FactoryServerPy", theComponentType.c_str());
+ obj = SALOME_LifeCycleCORBA(_name_service).FindOrLoad_Component("FactoryServer", theComponentType.c_str());
}
if (!CORBA::is_nil(obj)) {
{
CORBA::Object_var obj;
obj = _orb->string_to_object(theIOR.c_str());
-
+
if (!CORBA::is_nil(obj)) {
Engines::EngineComponent_var anEngine = Engines::EngineComponent::_narrow(obj);
return new SALOMEDS_Driver_i(anEngine, _orb);
# Executable scripts to be installed
SET(SCRIPTS
- SALOME_TestComponentPy.py
- TestComponentPy.py
+ SALOME_TestComponentPy.py
TestLogger.py
)
SALOME_INSTALL_SCRIPTS("${SCRIPTS}" ${KERNEL_salomescript_PYTHON})
# Files to be installed
# ===============================================================
#
-# header files
+# header files
# Scripts to be installed
dist_salomescript_PYTHON = \
SALOME_TestComponentPy.py \
- TestComponentPy.py \
TestLogger.py
#
command = ['TestUtils']
ret = os.spawnvp(os.P_WAIT, command[0], command)
-# kill Test process
+# kill Test process
TestKiller.killProcess(runSalome.process_id)