Use default value in os.getenv (fix bug for PYTHONPATH).
Introduce OMNIORB_USER_PATH variable.
#clean appli
-DELCOM="rm -rf bin lib share doc idl env.d envd USERS getAppliPath.py searchFreePort.sh runAppli runConsole runSession runRemote.sh runTests SalomeApp.xml runSalomeScript update_catalogs.py kill_remote_containers.py *.pyc *~ .bashrc"
+DELCOM="rm -rf bin lib share doc idl env.d envd USERS getAppliPath.py runAppli runConsole runSession runRemote.sh SalomeApp.xml runSalomeScript update_catalogs.py kill_remote_containers.py salome *.pyc *~ .bashrc"
DOIT="false"
if [ $# -gt 0 ]
then
if [ "x$1" == "x-f" ]
- then
+ then
DOIT="true"
fi
fi
fi
fi
-if [ $DOIT == "true" ]
+if [ $DOIT == "true" ]
then
$DELCOM
fi
for fn in ('envd',
'getAppliPath.py',
'kill_remote_containers.py',
-# 'searchFreePort.sh', # REMOVED
- 'runAppli', # OBSOLETE (replaced by salome.py)
- 'runConsole', # OBSOLETE (replaced by salome.py)
+ 'runAppli', # OBSOLETE (replaced by salome)
+ 'runConsole', # OBSOLETE (replaced by salome)
'runRemote.sh',
'runSalomeScript',
- 'runSession', # OBSOLETE (replaced by salome.py)
-# 'runTests', # REMOVED
- 'salome.py',
+ 'runSession', # OBSOLETE (replaced by salome)
+ 'salome',
'update_catalogs.py',
'.bashrc',
):
getAppliPath.py
update_catalogs.py
kill_remote_containers.py
- salome.py
+ salome # this is the Python launcher (without .py extension to avoid conflicts when importing salome python package)
)
SALOME_INSTALL_SCRIPTS("${SCRIPTS}" ${KERNEL_salomescript_SCRIPTS}/appliskel)
getAppliPath.py \
update_catalogs.py \
kill_remote_containers.py \
- salome.py
+ salome # this is the Python launcher (without .py extension to avoid conflicts when importing salome python package)
install-data-hook:
@for f in $(dist_appliskel_PYTHON) ; do \
###############################################
-APPLI_HOME=`dirname $0`
+#APPLI_HOME=`dirname $0`
+APPLI_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# --- retrieve APPLI path, relative to $HOME, set ${APPLI}
. ${HOME}/${APPLI}/envd ${HOME}/${APPLI}
+#export OMNIORB_USER_PATH="${HOME}/.salomeConfig/USERS"
+export OMNIORB_USER_PATH="${APPLI}/USERS"
+
# --- if mpi lam, start lam (seems safe to be done several times)
# (manual stop with lamhalt)
. ${HOME}/${APPLI}/envd ${HOME}/${APPLI}
+#export OMNIORB_USER_PATH="${HOME}/.salomeConfig/USERS"
+export OMNIORB_USER_PATH="${APPLI}/USERS"
+
# --- open a Python interpreter with SALOME environment
${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python -i ${KERNEL_ROOT_DIR}/bin/salome/salomeConsole.py $*
export NSPORT=$2
# Get (in bash) the configuration filename from (Python) ORBConfigFile return values
-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})
+RETURN_VALUES=$(${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/ORBConfigFile.py ${OMNIORB_USER_PATH} ${NSHOST} ${NSPORT} with_username=${USER})
export OMNIORB_CONFIG=$(echo ${RETURN_VALUES} | cut -d' ' -f1)
#go to the requested working directory if any
. ${HOME}/${APPLI}/envd ${HOME}/${APPLI}
+#export OMNIORB_USER_PATH="${HOME}/.salomeConfig/USERS"
+export OMNIORB_USER_PATH="${APPLI}/USERS"
+
# --- set the OMNIORB_CONFIG file and environment relative to this run of SALOME
# Usage: writeConfigFile PORT HOST
function writeConfigFile
export NSHOST=$2
# Get (in bash) the configuration filename from (Python) ORBConfigFile return values
- 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})
+ RETURN_VALUES=$(${KERNEL_ROOT_DIR}/bin/salome/envSalome.py python ${KERNEL_ROOT_DIR}/bin/salome/ORBConfigFile.py ${OMNIORB_USER_PATH} ${NSHOST} ${NSPORT} with_username=${USER})
export OMNIORB_CONFIG=$(echo ${RETURN_VALUES} | cut -d' ' -f1)
}
if test "x${NSHOST}" == "xlocalhost"; then
#MACHINE and PORT are not given
# --- set omniORB configuration to current session if any
- fileOmniConfig=${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
+ fileOmniConfig=${OMNIORB_USER_PATH}/.omniORB_${USER}_last.cfg
if [ -f $fileOmniConfig ]; then
- export OMNIORB_CONFIG=${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
+ export OMNIORB_CONFIG=${OMNIORB_USER_PATH}/.omniORB_${USER}_last.cfg
# --- set environment variables for port and hostname of NamingService
export NSHOST=`${KERNEL_ROOT_DIR}/bin/salome/NSparam.py host`
export NSPORT=`${KERNEL_ROOT_DIR}/bin/salome/NSparam.py port`
--- /dev/null
+#! /usr/bin/env python
+
+import os
+import sys
+import glob
+
+# Preliminary work to initialize path to SALOME Python modules
+def __initialize():
+ currentPath = os.path.dirname(__file__)
+ homePath = os.path.realpath(os.path.expanduser('~'))
+ appliPath = os.path.relpath(currentPath, homePath)
+
+ pattern = "/bin/salome/appliskel"
+ if appliPath.endswith(pattern):
+ appliPath = appliPath[:-len(pattern)]
+
+ absoluteAppliPath = os.path.join(homePath, appliPath)
+ os.environ['APPLI'] = appliPath # needed to convert .sh environment files
+ os.environ['ABSOLUTE_APPLI_PATH'] = absoluteAppliPath
+
+ # define folder to store omniorb config (initially in virtual application folder)
+ #omniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
+ omniorbUserPath = os.path.join(homePath, appliPath, "USERS")
+ os.environ['OMNIORB_USER_PATH'] = omniorbUserPath
+ if not os.path.exists(omniorbUserPath):
+ os.makedirs(omniorbUserPath)
+
+ sys.path[:0] = [absoluteAppliPath+'/bin/salome']
+# End of preliminary work
+
+def __listDirectory(path):
+ allFiles = []
+ for root, dirs, files in os.walk(path):
+ configFileNames = glob.glob(os.path.join(root,'*.cfg')) + glob.glob(os.path.join(root,'*.sh'))
+ allFiles += configFileNames
+ return allFiles
+#
+
+def __getConfigFileNamesDefault():
+ absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
+ envdDir = absoluteAppliPath + '/env.d'
+ if os.path.isdir(envdDir):
+ configFileNames = __listDirectory(envdDir)
+ else:
+ configFileNames = []
+
+ return configFileNames
+#
+
+def __getConfigFileNames(args):
+ # special case: configuration files are provided by user
+ # Search for command-line argument(s) --config=file1,file2,..., filen
+ # Search for command-line argument(s) --config=dir1,dir2,..., dirn
+ 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) ]
+ allLists = [ x.replace(configOptionPrefix, '') for x in configArgs ]
+
+ configFileNames = []
+ for currentList in allLists:
+ elements = currentList.split(',')
+ for elt in elements:
+ elt = os.path.realpath(os.path.expanduser(elt))
+ if os.path.isdir(elt):
+ configFileNames += __listDirectory(elt)
+ else:
+ configFileNames += elt
+
+ 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, SalomeRunnerException
+ try:
+ 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!'
+
+ except SalomeRunnerException, e:
+ import logging
+ logging.getLogger("salome").error(e)
+ sys.exit(1)
+#
+++ /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!'
-#
import os, sys, pickle, signal, commands,glob
from salome_utils import verbose
-import Utils_Identity
import salome_utils
def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None):
def appliCleanOmniOrbConfig(port):
"""
Remove omniorb config files related to the port in SALOME application:
- - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
- - ${HOME}/${APPLI}/USERS/.omniORB_${USER}_last.cfg
+ - ${OMNIORB_USER_PATH}/.omniORB_${USER}_${HOSTNAME}_${NSPORT}.cfg
+ - ${OMNIORB_USER_PATH}/.omniORB_${USER}_last.cfg
the last is removed only if the link points to the first file.
"""
from salome_utils import generateFileName, getUserName
- home = os.getenv("HOME")
- appli = os.getenv("APPLI")
- if appli is None:
+ omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
+ if omniorbUserPath is None:
#Run outside application context
pass
else:
- dir = os.path.join(os.path.realpath(home), appli,"USERS")
- omniorb_config = generateFileName(dir, prefix="omniORB",
+ omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
extension="cfg",
hidden=True,
with_username=True,
with_hostname=True,
with_port=port)
- last_running_config = generateFileName(dir, prefix="omniORB",
+ last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
with_username=True,
suffix="last",
extension="cfg",
if os.path.lexists(last_running_config):return
#try to relink last.cfg to an existing config file if any
- files = glob.glob(os.path.join(os.environ["HOME"],Utils_Identity.getapplipath(),
- "USERS",".omniORB_"+getUserName()+"_*.cfg"))
+ files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+getUserName()+"_*.cfg"))
current_config=None
current=0
for f in files:
from salome_utils import generateFileName
# set OMNIORB_CONFIG variable to the proper file
- home = os.getenv("HOME")
- appli = os.getenv("APPLI")
+ omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
kwargs = {}
- if appli is not None:
- home = os.path.join(os.path.realpath(home), appli,"USERS")
+ if omniorbUserPath is not None:
kwargs["with_username"]=True
- pass
- omniorb_config = generateFileName(home, prefix="omniORB",
+ omniorb_config = generateFileName(omniorbUserPath, prefix="omniORB",
extension="cfg",
hidden=True,
with_hostname=True,
# copied from python 2.6.8 Lib.ConfigParser.py
# modified (see code comments) to handle duplicate keys
- def _read(self, fp, name):
+ def _read(self, fp, fpname):
"""Parse a sectioned setup file.
The sections in setup file contains a title line at the top,
# raised at the end of the file and will contain a
# list of all bogus lines
if not e:
- e = ParsingError(fpname)
+ e = ConfigParser.ParsingError(fpname)
e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
if e:
if args['wake_up_session']:
if "OMNIORB_CONFIG" not in os.environ:
from salome_utils import generateFileName
- home = os.getenv("HOME")
- appli = os.getenv("APPLI")
+ omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
kwargs={}
- if appli is not None:
- home = os.path.join(os.path.realpath(home), appli,"USERS")
- kwargs["with_username"] = True
- pass
- last_running_config = generateFileName(home, prefix="omniORB",
+ if omniorbUserPath is not None:
+ kwargs["with_username"]=True
+
+ last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
suffix="last",
extension="cfg",
hidden=True,
# Save Naming service port name into
# the file args["ns_port_log_file"]
if args.has_key('ns_port_log_file'):
- home = os.environ['HOME']
- appli= os.environ.get("APPLI")
- if appli is not None:
- home = os.path.join(os.path.realpath(home), appli, "USERS")
- file_name = os.path.join(home, args["ns_port_log_file"])
+ omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
+ file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
f = open(file_name, "w")
f.write(os.environ['NSPORT'])
f.close()
# -----------------------------------------------------------------------------
if __name__ == "__main__":
+
+ ### TEMP ###
+ #homePath = os.path.realpath(os.path.expanduser('~'))
+ #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
+ appli = os.getenv("APPLI")
+ defaultOmniorbUserPath = os.path.join(appli, "/USERS")
+ os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
+ ############
+
runSalome()
#
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'
+ omniorbUserPath = os.environ['OMNIORB_USER_PATH']
+ fileOmniConfig = omniorbUserPath + '/.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
os.environ['NSPORT'] = port
os.environ['NSHOST'] = host
- absoluteAppliPath = os.environ['ABSOLUTE_APPLI_PATH']
- path = absoluteAppliPath + '/USERS'
+ path = os.environ['OMNIORB_USER_PATH']
kwargs = {'with_username' : os.environ['USER']}
from ORBConfigFile import writeORBConfigFile
import orbmodule
from runSalome import *
-import Utils_Identity
-files = glob.glob(os.path.join(os.environ["HOME"],Utils_Identity.getapplipath(),
- "USERS",".omniORB_"+salome_utils.getUserName()+"_*.cfg"))
+omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
+files = glob.glob(os.path.join(omniorbUserPath,".omniORB_"+salome_utils.getUserName()+"_*.cfg"))
filename=""
if len(files)==1:
import subprocess
import platform
+
+"""
+Define a specific exception class to manage exceptions related to SalomeRunner
+"""
+class SalomeRunnerException(Exception):
+ """Report error messages to the user interface of SalomeRunner."""
+#
+
+
"""
The SalomeRunner class in an API to configure SALOME environment then
start SALOME using a single python command.
to .cfg format before setting the environment.
"""
def __init__(self, configFileNames=[]):
+ if len(configFileNames) == 0:
+ raise SalomeRunnerException("No configuration files given")
+
for filename in configFileNames:
basename, extension = os.path.splitext(filename)
if extension == ".cfg":
# Automatically cleans up the file
temp.close()
else:
- self._getLogger().warning("Unrecognized extension for configuration file: %s", filename)
+ 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']
+ absoluteAppliPath = os.getenv('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)
+ self.__addToReserved('PATH', value)
#
"""Append value to LD_LIBRARY_PATH environment variable"""
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)
+ self.getLogger().warning("Environment variable already existing and not overwritten: %s", name)
return
if env:
- self._getLogger().info("Overwriting environment variable: %s", name)
+ 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)
+ self.getLogger().debug("Set environment variable: %s=%s", name, value)
os.environ[name] = value
#
}
if not command in availableCommands.keys():
- self._getLogger().error("Unrecognized command: %s.", command)
+ self.getLogger().error("Unrecognized command: %s.", command)
self._usage()
sys.exit(1)
try:
getattr(self, command)(options) # run appropriate method
except AttributeError:
- self._getLogger().error("Method %s is not implemented.", command)
+ self.getLogger().error("Method %s is not implemented.", command)
sys.exit(1)
#
self.setEnviron(key, val, overwrite=True)
pass
- sys.path[:0] = os.environ['PYTHONPATH'].split(':')
+ sys.path[:0] = os.getenv('PYTHONPATH','').split(':')
#
def __addToReserved(self, name, value):
return
value = os.path.expandvars(value) # expand environment variables
- self._getLogger().debug("Add to %s: %s", name, value)
+ self.getLogger().debug("Add to %s: %s", name, value)
env = os.getenv(name, None)
if env is None:
os.environ[name] = value
proc = subprocess.Popen(args, shell=False, close_fds=True)
proc.wait()
else:
- absoluteAppliPath = os.environ['ABSOLUTE_APPLI_PATH']
+ absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
cmd = ["/bin/bash", "--rcfile", absoluteAppliPath + "/.bashrc" ]
proc = subprocess.Popen(cmd, shell=False, close_fds=True)
proc.wait()
# 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']
+ if hasattr(self, '_logger'):
+ 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):
+ def getLogger(self):
if not hasattr(self, '_logger'):
self._logger = logging.getLogger(__name__)
#self._logger.setLevel(logging.DEBUG)
from salome_utils import generateFileName, getHostName
hostname = getHostName()
#
- home = os.getenv("HOME")
- appli = os.getenv("APPLI")
+ omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
kwargs={}
- if appli is not None:
- home = os.path.join(os.path.realpath(home), appli, "USERS")
+ if omniorbUserPath is not None:
kwargs["with_username"]=True
#
from ORBConfigFile import writeORBConfigFile
- omniorb_config, giopsize = writeORBConfigFile(home, hostname, nsport, kwargs)
+ omniorb_config, giopsize = writeORBConfigFile(omniorbUserPath, hostname, nsport, kwargs)
args['port'] = os.environ['NSPORT']
#
if save_config:
- last_running_config = generateFileName(home, prefix="omniORB",
+ last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
suffix="last",
extension="cfg",
hidden=True,
print "- KO: port is busy"
pass
#
-
+
print "Searching for a free port for naming service:",
#
NSPORT=NSPORT+1
pass
#
-
+
return