From: vsr Date: Tue, 9 Dec 2014 06:46:16 +0000 (+0300) Subject: Merge remote branch 'origin/agr/python_refactoring' into V7_5_BR X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=55d3ab2d9573165ef43821b778581ac47164dde9;hp=0b560ba293f96f4698a95237ef1191f73f7ffcd8;p=modules%2Fyacs.git Merge remote branch 'origin/agr/python_refactoring' into V7_5_BR --- diff --git a/bin/NSparam.py b/bin/NSparam.py index cde5c7cd3..f1c2dd35c 100755 --- a/bin/NSparam.py +++ b/bin/NSparam.py @@ -35,13 +35,13 @@ def getNSparams(info=""): else print 2 strings on stdout on one line: host port """ from salome_utils import getORBcfgInfo - my_version, my_host, my_port = getORBcfgInfo() + _, my_host, my_port = getORBcfgInfo() if info=='host': - os.environ['NSHOST']=my_host + os.environ['NSHOST'] = my_host return my_host pass elif info=='port': - os.environ['NSPORT']=my_port + os.environ['NSPORT'] = my_port return my_port pass else: diff --git a/bin/ORBConfigFile.py b/bin/ORBConfigFile.py index 02bdf59a4..2c693445d 100644 --- a/bin/ORBConfigFile.py +++ b/bin/ORBConfigFile.py @@ -40,7 +40,7 @@ def writeORBConfigFile(path, host, port, kwargs={}): from omniORB import CORBA prefix = "" if CORBA.ORB_ID == "omniORB4" else "ORB" - GIOP_MaxMsgSize=2097152000 # 2 GBytes + GIOP_MaxMsgSize = 2097152000 # 2 GBytes orbdata = [] orbdata.append("%sInitRef = NameService=corbaname::%s:%s"%(prefix,host,port)) @@ -49,16 +49,15 @@ def writeORBConfigFile(path, host, port, kwargs={}): orbdata.append("%smaxGIOPConnectionPerServer = 50 # to allow containers parallel launch"%(prefix)) orbdata.append("") - f = open(omniorb_config, "w") - f.write("\n".join(orbdata)) - f.close() + with open(omniorb_config, "w") as f: + f.write("\n".join(orbdata)) return [ omniorb_config, GIOP_MaxMsgSize ] # ----------------------------------------------------------------------------- if __name__ == "__main__": - import sys, getopt + import sys path = sys.argv[1] host = sys.argv[2] diff --git a/bin/PortManager.py b/bin/PortManager.py index 0d01ce950..465ac8784 100644 --- a/bin/PortManager.py +++ b/bin/PortManager.py @@ -25,9 +25,9 @@ import os import sys try: - import cPickle as pickle + import cPickle as pickle #@UnusedImport except: - import pickle + import pickle #@Reimport import logging def createLogger(): @@ -88,7 +88,7 @@ def __isNetworkConnectionActiveOnPort(port): # netstat options -l and -t are unavailable # grep command is unavailable from subprocess import Popen, PIPE - (stdout, stderr) = Popen(['netstat','-an'], stdout=PIPE).communicate() + stdout, _ = Popen(['netstat','-an'], stdout=PIPE).communicate() import StringIO buf = StringIO.StringIO(stdout) ports = buf.readlines() diff --git a/bin/addToKillList.py b/bin/addToKillList.py index 7d688aca2..24ca6783f 100755 --- a/bin/addToKillList.py +++ b/bin/addToKillList.py @@ -22,7 +22,7 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -import os, sys, pickle, string, signal +import os, sys, pickle, signal from launchConfigureParser import verbose ########## adds to the kill list of SALOME one more process ########## @@ -60,7 +60,7 @@ def addToKillList(command_pid, command, port=None): # check if PID is already in dictionary already_in=False for process_id in process_ids: - for pid, cmd in process_id.items(): + for pid in process_id.keys(): if int(pid) == int(command_pid): already_in=True break diff --git a/bin/appli_gen.py b/bin/appli_gen.py index 199790f80..5b6ee5411 100644 --- a/bin/appli_gen.py +++ b/bin/appli_gen.py @@ -19,24 +19,25 @@ # 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 +# See http://www.salome-platform.org or email : webmaster.salome@opencascade.com # ## \file appli_gen.py # Create a %SALOME application (virtual Salome installation) # -usage="""usage: %prog [options] +usage = """%(prog)s [options] Typical use is: - python appli_gen.py + python %(prog)s Typical use with options is: - python appli_gen.py --verbose --prefix= --config= + python %(prog)s --verbose --prefix= --config= """ -import os, glob, string, sys, re +import argparse +import os +import sys import shutil -import xml.sax -import optparse import virtual_salome +import xml.sax # --- names of tags in XML configuration file appli_tag = "application" @@ -69,13 +70,13 @@ class xml_parser: parser.parse(fileName) pass - def boolValue( self, str ): - if str in ("yes", "y", "1"): + def boolValue( self, text): + if text in ("yes", "y", "1"): return 1 - elif str in ("no", "n", "0"): + elif text in ("no", "n", "0"): return 0 else: - return str + return text pass def startElement(self, name, attrs): @@ -120,7 +121,7 @@ class xml_parser: pass def endElement(self, name): - p = self.space.pop() + self.space.pop() self.current = None pass @@ -150,20 +151,20 @@ class params: def makedirs(namedir): if os.path.exists(namedir): - dirbak=namedir+".bak" + dirbak = namedir+".bak" if os.path.exists(dirbak): shutil.rmtree(dirbak) - os.rename(namedir,dirbak) + os.rename(namedir, dirbak) os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines os.makedirs(namedir) -def install(prefix,config_file,verbose=0): - home_dir=os.path.abspath(os.path.expanduser(prefix)) - filename=os.path.abspath(os.path.expanduser(config_file)) - _config={} +def install(prefix, config_file, verbose=0): + home_dir = os.path.abspath(os.path.expanduser(prefix)) + filename = os.path.abspath(os.path.expanduser(config_file)) + _config = {} try: - p = xml_parser(filename) - _config = p.config + parser = xml_parser(filename) + _config = parser.config except xml.sax.SAXParseException, inst: print inst.getMessage() print "Configure parser: parse error in configuration file %s" % filename @@ -177,23 +178,23 @@ def install(prefix,config_file,verbose=0): pass if verbose: - for cle in _config.keys(): - print cle, _config[cle] + for cle,val in _config.items(): + print cle, val pass - for module in _config.get("modules",[]): + for module in _config.get("modules", []): if _config.has_key(module): print "--- add module ", module, _config[module] options = params() - options.verbose=verbose - options.clear=0 - options.prefix=home_dir - options.module=_config[module] + options.verbose = verbose + options.clear = 0 + options.prefix = home_dir + options.module = _config[module] virtual_salome.link_module(options) pass pass - appliskel_dir=os.path.join(home_dir,'bin','salome','appliskel') + appliskel_dir = os.path.join(home_dir, 'bin', 'salome', 'appliskel') for fn in ('envd', 'getAppliPath.py', @@ -211,94 +212,87 @@ def install(prefix,config_file,verbose=0): pass if filename != os.path.join(home_dir,"config_appli.xml"): - command = "cp -p " + filename + ' ' + os.path.join(home_dir,"config_appli.xml") - os.system(command) + shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml")) pass # Creation of env.d directory virtual_salome.mkdir(os.path.join(home_dir,'env.d')) if _config.has_key("prereq_path") and os.path.isfile(_config["prereq_path"]): - command='cp -p ' + _config["prereq_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.sh') - os.system(command) + shutil.copyfile(_config["prereq_path"], + os.path.join(home_dir, 'env.d', 'envProducts.sh')) pass else: print "WARNING: prerequisite file does not exist" pass if _config.has_key("context_path") and os.path.isfile(_config["context_path"]): - command='cp -p ' + _config["context_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.cfg') - os.system(command) + shutil.copyfile(_config["context_path"], + os.path.join(home_dir, 'env.d', 'envProducts.cfg')) pass else: print "WARNING: context file does not exist" pass if _config.has_key("system_conf_path") and os.path.isfile(_config["system_conf_path"]): - command='cp -p ' + _config["system_conf_path"] + ' ' + os.path.join(home_dir,'env.d','envConfSystem.sh') - os.system(command) + shutil.copyfile(_config["system_conf_path"], + os.path.join(home_dir, 'env.d', 'envConfSystem.sh')) pass # Create environment file: configSalome.sh - f =open(os.path.join(home_dir,'env.d','configSalome.sh'),'w') - for module in _config.get("modules",[]): - command='export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n' - f.write(command) - pass - if _config.has_key("samples_path"): - command='export DATA_DIR=' + _config["samples_path"] +'\n' - f.write(command) - pass - if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): - command='export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' - f.write(command) - - f.close() + with open(os.path.join(home_dir, 'env.d', 'configSalome.sh'),'w') as f: + for module in _config.get("modules", []): + command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n' + f.write(command) + pass + if _config.has_key("samples_path"): + command = 'export DATA_DIR=' + _config["samples_path"] +'\n' + f.write(command) + pass + if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): + command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' + f.write(command) # Create configuration file: configSalome.cfg - f =open(os.path.join(home_dir,'env.d','configSalome.cfg'),'w') - command = "[SALOME ROOT_DIR (modules) Configuration]\n" - f.write(command) - for module in _config.get("modules",[]): - command=module + '_ROOT_DIR=${HOME}/${APPLI}\n' + with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f: + command = "[SALOME ROOT_DIR (modules) Configuration]\n" f.write(command) - pass - if _config.has_key("samples_path"): - command='DATA_DIR=' + _config["samples_path"] +'\n' - f.write(command) - pass - if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): - command='USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' - f.write(command) - - f.close() + for module in _config.get("modules", []): + command = module + '_ROOT_DIR=${HOME}/${APPLI}\n' + f.write(command) + pass + if _config.has_key("samples_path"): + command = 'DATA_DIR=' + _config["samples_path"] +'\n' + f.write(command) + pass + if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]): + command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n' + f.write(command) # Create environment file: configGUI.sh - f =open(os.path.join(home_dir,'env.d','configGUI.sh'),'w') - command = """export SalomeAppConfig=${HOME}/${APPLI} + with open(os.path.join(home_dir, 'env.d', 'configGUI.sh'),'w') as f: + command = """export SalomeAppConfig=${HOME}/${APPLI} export SUITRoot=${HOME}/${APPLI}/share/salome export DISABLE_FPE=1 export MMGT_REENTRANT=1 """ - f.write(command) - f.close() + f.write(command) # Create configuration file: configGUI.cfg - f =open(os.path.join(home_dir,'env.d','configGUI.cfg'),'w') - command = """[SALOME GUI Configuration] + with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f: + command = """[SALOME GUI Configuration] SalomeAppConfig=${HOME}/${APPLI} SUITRoot=${HOME}/${APPLI}/share/salome DISABLE_FPE=1 MMGT_REENTRANT=1 """ - f.write(command) - f.close() + f.write(command) #SalomeApp.xml file - f =open(os.path.join(home_dir,'SalomeApp.xml'),'w') - command=""" + with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f: + command = """
@@ -318,37 +312,38 @@ MMGT_REENTRANT=1
""" - mods=[] - #Keep all modules except KERNEL and GUI - for m in _config.get("modules",[]): - if m in ("KERNEL","GUI"):continue - mods.append(m) - f.write(command % ",".join(mods)) - f.close() + mods = [] + #Keep all modules except KERNEL and GUI + for module in _config.get("modules", []): + if module in ("KERNEL","GUI"): + continue + mods.append(module) + f.write(command % ",".join(mods)) #Add USERS directory with 777 permission to store users configuration files - users_dir=os.path.join(home_dir,'USERS') + users_dir = os.path.join(home_dir,'USERS') makedirs(users_dir) os.chmod(users_dir, 0777) def main(): - parser = optparse.OptionParser(usage=usage) + parser = argparse.ArgumentParser(usage=usage) - parser.add_option('--prefix', dest="prefix", default='.', - help="Installation directory (default .)") + parser.add_argument('--prefix', default='.', metavar="", + help="Installation directory (default %(default)s)") - parser.add_option('--config', dest="config", default='config_appli.xml', - help="XML configuration file (default config_appli.xml)") + parser.add_argument('--config', default='config_appli.xml', + metavar="", + help="XML configuration file (default %(default)s)") - parser.add_option('-v', '--verbose', action='count', dest='verbose', + parser.add_argument('-v', '--verbose', action='count', default=0, help="Increase verbosity") - options, args = parser.parse_args() + options = parser.parse_args() if not os.path.exists(options.config): - print "ERROR: config file %s does not exist. It is mandatory." % options.config - sys.exit(1) + print "ERROR: config file %s does not exist. It is mandatory." % options.config + sys.exit(1) - install(prefix=options.prefix,config_file=options.config,verbose=options.verbose) + install(prefix=options.prefix, config_file=options.config, verbose=options.verbose) pass # ----------------------------------------------------------------------------- diff --git a/bin/appliskel/runSalomeScript b/bin/appliskel/runSalomeScript index 5b005d587..bba7beda0 100755 --- a/bin/appliskel/runSalomeScript +++ b/bin/appliskel/runSalomeScript @@ -22,6 +22,13 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # +############################################### +############### IMPORTANT NOTE ################ +############################################### +# The runSalomeScript script is obsolete. # +# Please consider the new salome launcher. # +############################################### + import os,sys,optparse import socket,shutil import re diff --git a/bin/appliskel/salome_starter.py b/bin/appliskel/salome_starter.py index 215a49e8d..7eb0a7e5c 100644 --- a/bin/appliskel/salome_starter.py +++ b/bin/appliskel/salome_starter.py @@ -33,7 +33,7 @@ def __detectAppliPath(fromPath, launcherFile): if os.path.isdir(users_folder): return fromPath - pattern = "/bin/salome/appliskel" + pattern = os.path.sep + os.path.join("bin", "salome", "appliskel") if fromPath.endswith(pattern): currentPath = __detectAppliPath(fromPath[:-len(pattern)], launcherFile) if not currentPath is None: @@ -61,7 +61,7 @@ def initialize(launcherPath, launcherFile): os.environ['APPLI'] = appliPath # needed to convert .sh environment files os.environ['ABSOLUTE_APPLI_PATH'] = absoluteAppliPath - sys.path[:0] = [absoluteAppliPath+'/bin/salome'] + sys.path[:0] = [os.path.join(absoluteAppliPath, "bin", "salome")] # define folder to store omniorb config (initially in virtual application folder) try: diff --git a/bin/envSalome.py b/bin/envSalome.py index fb36c618d..3b7388f9f 100755 --- a/bin/envSalome.py +++ b/bin/envSalome.py @@ -36,7 +36,7 @@ import sys import setenv kernel_root=os.getenv("KERNEL_ROOT_DIR") -sys.path[:0]=[kernel_root+"/bin/salome"] +sys.path[:0]=[os.path.join(kernel_root,"bin","salome")] argv = sys.argv[1:] sys.argv = argv[1:] diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py index 385454a9a..b1dcaab42 100755 --- a/bin/killSalomeWithPort.py +++ b/bin/killSalomeWithPort.py @@ -32,8 +32,10 @@ # import os, sys, pickle, signal, commands,glob +import subprocess +import shlex from salome_utils import verbose -import salome_utils + def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None): """ @@ -59,7 +61,7 @@ def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None): except: pass - from salome_utils import generateFileName, getTmpDir + from salome_utils import generateFileName, getLogDir dir = "" if not hostname: hostname = os.getenv("NSHOST") @@ -70,7 +72,7 @@ def getPiDict(port,appname='salome',full=True,hidden=True,hostname=None): if hidden: # new-style dot-prefixed pidict files # are in the system-dependant temporary diretory - dir = getTmpDir() + dir = getLogDir() else: # old-style non-dot-prefixed pidict files # are in the user's home directory @@ -221,20 +223,15 @@ def __killMyPort(port, filedict): try: with open(filedict, 'r') as fpid: # - from salome_utils import generateFileName - if sys.platform == "win32": - username = os.getenv( "USERNAME" ) - else: - username = os.getenv('USER') - path = os.path.join('/tmp/logs', username) - fpidomniNames = generateFileName(path, + from salome_utils import generateFileName, getLogDir + fpidomniNames = generateFileName(getLogDir(), prefix="", suffix="Pid_omniNames", extension="log", with_port=port) if not sys.platform == 'win32': - cmd = 'pid=`ps -eo pid,command | egrep "[0-9] omniNames -start %s"` ; echo $pid > %s' % ( str(port), fpidomniNames ) - a = os.system(cmd) + cmd = 'pid=$(ps -eo pid,command | egrep "[0-9] omniNames -start {0}") ; echo $pid > {1}'.format(port, fpidomniNames ) + subprocess.call(cmd, shell=True) pass try: with open(fpidomniNames) as fpidomniNamesFile: @@ -245,7 +242,7 @@ def __killMyPort(port, filedict): try: pidfield = l.split()[0] # pid should be at the first position if sys.platform == "win32": - import win32pm + import win32pm #@UnresolvedImport if verbose(): print 'stop process '+pidfield+' : omniNames' win32pm.killpid(int(pidfield),0) else: @@ -267,12 +264,10 @@ def __killMyPort(port, filedict): if verbose(): print "stop process %s : %s"% (pid, cmd[0]) if cmd[0] == "omniNames": if not sys.platform == 'win32': - import subprocess - import shlex proc1 = subprocess.Popen(shlex.split('ps -eo pid,command'),stdout=subprocess.PIPE) proc2 = subprocess.Popen(shlex.split('egrep "[0-9] omniNames -start"'),stdin=proc1.stdout, stdout=subprocess.PIPE,stderr=subprocess.PIPE) proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits. - out,err=proc2.communicate() + out,_ = proc2.communicate() # out looks like: PID omniNames -start PORT # extract omninames pid and port number @@ -286,7 +281,7 @@ def __killMyPort(port, filedict): from PortManager import releasePort releasePort(omniNamesPort) os.kill(int(omniNamesPid),signal.SIGKILL) - except (ImportError, AttributeError, OSError) as e: + except (ImportError, AttributeError, OSError): pass except: import traceback @@ -294,7 +289,7 @@ def __killMyPort(port, filedict): try: if sys.platform == "win32": - import win32pm + import win32pm #@UnresolvedImport @Reimport win32pm.killpid(int(pid),0) else: os.kill(int(pid),signal.SIGKILL) @@ -312,6 +307,7 @@ def __killMyPort(port, filedict): # os.remove(filedict) cmd='ps -eo pid,command | egrep "[0-9] omniNames -start '+str(port)+'" | sed -e "s%[^0-9]*\([0-9]*\) .*%\\1%g"' +# pid = subprocess.check_output(shlex.split(cmd)) pid = commands.getoutput(cmd) a = "" while pid and len(a.split()) < 2: @@ -375,7 +371,7 @@ def killMyPort(port): time.sleep(3) # wait a little, then kill processes (should be done if shutdown procedure hangs up) try: - import PortManager + import PortManager # do not remove! Test for PortManager availability! filedict = getPiDict(port) #filedict = __guessPiDictFilename(port) import glob @@ -414,7 +410,7 @@ def killMyPortSpy(pid, port): dt = 1.0 while 1: if sys.platform == "win32": - from win32pm import killpid + from win32pm import killpid #@UnresolvedImport if killpid(int(pid), 0) != 0: return else: @@ -437,7 +433,7 @@ def killMyPortSpy(pid, port): orb = omniORB.CORBA.ORB_init(sys.argv, omniORB.CORBA.ORB_ID) import SALOME_NamingServicePy ns = SALOME_NamingServicePy.SALOME_NamingServicePy_i(orb) - import SALOME + import SALOME #@UnresolvedImport @UnusedImport session = ns.Resolve("/Kernel/Session") assert session except: @@ -472,7 +468,7 @@ if __name__ == "__main__": sys.exit(0) pass try: - from salomeContextUtils import setOmniOrbUserPath + from salomeContextUtils import setOmniOrbUserPath #@UnresolvedImport setOmniOrbUserPath() except Exception, e: print e diff --git a/bin/launchConfigureParser.py b/bin/launchConfigureParser.py index 9c4c39e0a..4d003a386 100755 --- a/bin/launchConfigureParser.py +++ b/bin/launchConfigureParser.py @@ -26,7 +26,7 @@ import xml.sax import optparse import types -from salome_utils import verbose, setVerbose, getPortNumber, getHomeDir +from salome_utils import verbose, getPortNumber, getHomeDir from salomeContextUtils import getScriptsAndArgs @@ -105,11 +105,13 @@ def version(): try: filename = None root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found - if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ): - filename = root_dir + "/bin/salome/VERSION" + version_file = os.path.join(root_dir, 'bin', 'salome', 'VERSION') + if root_dir and os.path.exists( version_file ): + filename = version_file root_dir = os.environ.get( 'GUI_ROOT_DIR', '' ) # GUI_ROOT_DIR "" if not found - if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ): - filename = root_dir + "/bin/salome/VERSION" + version_file = os.path.join(root_dir, 'bin', 'salome', 'VERSION') + if root_dir and os.path.exists( version_file ): + filename = version_file if filename: str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0" match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str ) @@ -127,7 +129,12 @@ def version_id(fname): major = minor = release = dev1 = dev2 = 0 vers = fname.split(".") if len(vers) > 0: major = int(vers[0]) - if len(vers) > 1: minor = int(vers[1]) + try: + if len(vers) > 1: minor = int(vers[1]) + except ValueError: + # If salome version given is 7.DEV, the call to int('DEV') will fail with + # a ValueError exception + pass if len(vers) > 2: mr = re.search(r'^([0-9]+)([A-Z]|RC)?([0-9]*)',vers[2], re.I) if mr: @@ -160,15 +167,14 @@ def version_id(fname): ### def defaultUserFile(appname=salomeappname, cfgname=salomecfgname): v = version() - if v: v = ".%s" % v if sys.platform == "win32": - filename = os.path.join(getHomeDir(), "%s.xml%s" % (appname, v)) + filename = os.path.join(getHomeDir(), "{0}.xml.{1}".format(appname, v)) else: if cfgname: - filename = os.path.join(getHomeDir(), ".config", cfgname, "%src%s" % (appname, v)) + filename = os.path.join(getHomeDir(), ".config", cfgname, "{0}rc.{1}".format(appname, v)) pass else: - filename = os.path.join(getHomeDir(), ".%src%s" % (appname, v)) + filename = os.path.join(getHomeDir(), "{0}rc.{1}".format(appname, v)) pass pass return filename @@ -196,17 +202,17 @@ def userFile(appname, cfgname): # ... get all existing user preferences files if sys.platform == "win32": - files = glob.glob(os.path.join(getHomeDir(), "%s.xml.*" % appname)) + files = glob.glob(os.path.join(getHomeDir(), "{0}.xml.*".format(appname))) else: files = [] if cfgname: # Since v6.6.0 - in ~/.config/salome directory, without dot prefix - files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, "%src.*" % appname)) + files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, "{0}rc.*".format(appname))) # Since v6.5.0 - in ~/.config/salome directory, dot-prefixed (backward compatibility) - files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".%src.*" % appname)) + files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".{0}rc.*".format(appname))) pass # old style (before v6.5.0) - in ~ directory, dot-prefixed - files += glob.glob(os.path.join(getHomeDir(), ".%src.*" % appname)) + files += glob.glob(os.path.join(getHomeDir(), ".{0}rc.*".format(appname))) pass # ... loop through all files and find most appopriate file (with closest id) @@ -215,9 +221,9 @@ def userFile(appname, cfgname): for f in files: ff = os.path.basename( f ) if sys.platform == "win32": - match = re.search( r'^%s\.xml\.([a-zA-Z0-9.]+)$'%appname, ff ) + match = re.search( r'^{0}\.xml\.([a-zA-Z0-9.]+)$'.format(appname), ff ) else: - match = re.search( r'^\.?%src\.([a-zA-Z0-9.]+)$'%appname, ff ) + match = re.search( r'^\.?{0}rc\.([a-zA-Z0-9.]+)$'.format(appname), ff ) if match: ver = version_id(match.group(1)) if not ver: continue # bad version id -> skip file @@ -352,7 +358,7 @@ class xml_parser: pass def endElement(self, name): - p = self.space.pop() + self.space.pop() self.current = None if self.section != section_to_skip and name == sec_tag: self.section = section_to_skip @@ -903,10 +909,6 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn global args config_var = appname+'Config' - separator = ":" - if os.sys.platform == 'win32': - separator = ";" - # check KERNEL_ROOT_DIR kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None) if kernel_root_dir is None: @@ -941,20 +943,22 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn dirs = [] if os.getenv(config_var): if sys.platform == 'win32': - dirs += re.split(';', os.getenv(config_var)) + dirs += re.split(os.pathsep, os.getenv(config_var)) else: dirs += re.split('[;|:]', os.getenv(config_var)) gui_available = True - if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ): - dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"] + gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui') + if os.getenv("GUI_ROOT_DIR") and os.path.isdir( gui_resources_dir ): + dirs.append(gui_resources_dir) pass else: gui_available = False - if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ): - dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"] + kernel_resources_dir = os.path.join(os.getenv("KERNEL_ROOT_DIR"),'bin','salome','appliskel') + if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( kernel_resources_dir ): + dirs.append(kernel_resources_dir) pass - os.environ[config_var] = separator.join(dirs) + os.environ[config_var] = os.pathsep.join(dirs) dirs.reverse() # reverse order, like in "path" variable - FILO-style processing @@ -1176,7 +1180,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn #################################################### # Add values to args for add_opt in theAdditionalOptions: - cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest) + cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest) exec(cmd) #################################################### @@ -1191,15 +1195,15 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn dirs = re.split('[;]', os.environ[config_var] ) else: dirs = re.split('[;|:]', os.environ[config_var] ) - for m in args[modules_nam]: - if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m): - d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower() - d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources" + for module in args[modules_nam]: + if module not in ["KERNEL", "GUI", ""] and os.getenv("{0}_ROOT_DIR".format(module)): + d1 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources",module.lower()) + d2 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources") #if os.path.exists( "%s/%s.xml"%(d1, appname) ): - if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ): + if os.path.exists( os.path.join(d1,"{0}.xml".format(salomeappname)) ): dirs.append( d1 ) #elif os.path.exists( "%s/%s.xml"%(d2, appname) ): - elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ): + elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ): dirs.append( d2 ) else: #print "* '"+m+"' should be deleted from ",args[modules_nam] @@ -1231,6 +1235,6 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn args[useport_nam] = cmd_opts.use_port # return arguments - os.environ[config_var] = separator.join(dirs) + os.environ[config_var] = os.pathsep.join(dirs) #print "Args: ", args return args diff --git a/bin/nameserver.py b/bin/nameserver.py index ce1402ba7..ad302db2d 100755 --- a/bin/nameserver.py +++ b/bin/nameserver.py @@ -22,62 +22,42 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -import sys, os, re, socket +import os, sys, re, socket #import commands -from server import * +from server import Server from Utils_Identity import getShortHostName from launchConfigureParser import verbose # ----------------------------------------------------------------------------- class NamingServer(Server): - XTERM="" - USER=os.getenv('USER') - if USER is None: - USER='anonymous' - #os.system("mkdir -m 777 -p /tmp/logs") - LOGDIR="/tmp/logs/" + USER - - def initNSArgs(self): - 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" - + #XTERM = "" + #USER = os.getenv('USER') + #if USER is None: + # USER = 'anonymous' + #os.system("mkdir -m 777 -p /tmp/logs") + #LOGDIR = "/tmp/logs/" + USER + + def initNSArgs(self): + from salome_utils import getLogDir + upath = getLogDir() try: - os.mkdir(os.environ["BaseDir"] + "/logs") - os.chmod(os.environ["BaseDir"] + "/logs", 0777) + os.makedirs(upath, mode=0777) except: - #print "Can't create " + os.environ["BaseDir"] + "/logs" - pass - - upath = os.environ["BaseDir"] + "/logs/"; - if sys.platform == "win32": - upath += os.environ["Username"]; - else: - upath += os.environ["USER"]; - - try: - os.mkdir(upath) - except: - #print "Can't create " + upath - pass + pass if verbose(): print "Name Service... ", #hname=os.environ["HOST"] #commands.getoutput("hostname") if sys.platform == "win32": - hname=getShortHostName(); + hname = getShortHostName(); else: hname = socket.gethostname(); #print "hname=",hname - f=open(os.environ["OMNIORB_CONFIG"]) - ss=re.findall("NameService=corbaname::" + hname + ":\d+", f.read()) - if verbose(): print "ss = ", ss, - f.close() - sl=ss[0] + with open(os.environ["OMNIORB_CONFIG"]) as f: + ss = re.findall("NameService=corbaname::" + hname + ":\d+", f.read()) + if verbose(): print "ss = ", ss, + sl = ss[0] ll = sl.split(':') aPort = ll[-1] #aPort=(ss.join().split(':'))[2]; @@ -88,18 +68,18 @@ class NamingServer(Server): # it is cleaner on linux and it is a fix for salome since it is impossible to # remove the log files if the corresponding omniNames has not been killed. # \end{E.A.} - - upath += "/omniNames_%s"%(aPort) + + upath = os.path.join(upath, "omniNames_%s"%(aPort)) try: - os.mkdir(upath) + os.mkdir(upath) except: - #print "Can't create " + upath - pass - + #print "Can't create " + upath + pass + #os.system("touch " + upath + "/dummy") for fname in os.listdir(upath): try: - os.remove(upath + "/" + fname) + os.remove(upath + "/" + fname) except: pass #os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log") @@ -110,24 +90,24 @@ class NamingServer(Server): #print "port=", aPort if sys.platform == "win32": #print "start omniNames -start " + aPort + " -logdir " + upath - self.CMD=['omniNames', '-start' , aPort , '-nohostname', '-logdir' , os.path.realpath(upath), '-errlog', os.path.realpath(os.path.join(upath,'omniNameErrors.log'))] + self.CMD = ['omniNames', '-start' , aPort , '-nohostname', '-logdir' , os.path.realpath(upath), '-errlog', os.path.realpath(os.path.join(upath,'omniNameErrors.log'))] #os.system("start omniNames -start " + aPort + " -logdir " + upath) else: #self.CMD=['omniNames -start ' , aPort , ' -logdir ' , upath , ' &'] - self.CMD=['omniNames','-start' , aPort, '-logdir' , upath, '-errlog', upath+'/omniNameErrors.log'] + self.CMD = ['omniNames','-start' , aPort, '-logdir' , upath, '-errlog', upath+'/omniNameErrors.log'] #os.system("omniNames -start " + aPort + " -logdir " + upath + " &") if verbose(): print "... ok" if verbose(): print "to list contexts and objects bound into the context with the specified name : showNS " - def initArgs(self): + def initArgs(self): Server.initArgs(self) if sys.platform == "win32": - env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("PATH")] + env_ld_library_path = ['env', 'LD_LIBRARY_PATH=' + os.getenv("PATH")] else: - env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")] - self.CMD=['xterm', '-e']+ env_ld_library_path + ['python'] + env_ld_library_path = ['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")] + self.CMD = ['xterm', '-e']+ env_ld_library_path + ['python'] self.initNSArgs() # In LifeCycleCORBA, FactoryServer is started with rsh on the requested @@ -135,7 +115,7 @@ class NamingServer(Server): # 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 +# 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 diff --git a/bin/orbmodule.py b/bin/orbmodule.py index dc280ce81..97ef010bb 100755 --- a/bin/orbmodule.py +++ b/bin/orbmodule.py @@ -27,7 +27,7 @@ import sys,os,time import string -from nameserver import * +from nameserver import NamingServer from omniORB import CORBA from launchConfigureParser import verbose @@ -37,18 +37,18 @@ import CosNaming # ----------------------------------------------------------------------------- class client: - """Client for SALOME""" + """Client for SALOME""" - def __init__(self,args=None): + def __init__(self,args=None): # Initialise the ORB self.orb=CORBA.ORB_init(sys.argv, CORBA.ORB_ID) # Initialise the Naming Service self.initNS(args or {}) - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def initNS(self,args): + def initNS(self,args): # Obtain a reference to the root naming context obj = self.orb.resolve_initial_references("NameService") try: @@ -61,11 +61,11 @@ class client: # On lance le Naming Server (doit etre dans le PATH) test = True if args['wake_up_session']: - test = False - pass + test = False + pass if test: - NamingServer(args).run() - pass + NamingServer(args).run() + pass print "Searching Naming Service ", ncount=0 delta=0.1 @@ -86,42 +86,42 @@ class client: sys.exit(1) print " found in %s seconds " % ((ncount-1)*delta) - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def showNScontext(self,context,dec=''): + def showNScontext(self,context,dec=''): if not context: - print "[NS] No context" - return + print "[NS] No context" + return else: - print context + print context - bl,bi=context.list(0) + _,bi = context.list(0) if bi is not None: - ok,b=bi.next_one() - while(ok): + ok,b = bi.next_one() + while(ok): for s in b.binding_name : - print "%s%s.%s" %(dec,s.id,s.kind) - if s.kind == "dir": - obj=context.resolve([s]) + print "%s%s.%s" %(dec,s.id,s.kind) + if s.kind == "dir": + obj = context.resolve([s]) scontext = obj._narrow(CosNaming.NamingContext) self.showNScontext(scontext,dec=dec+' ') - ok,b=bi.next_one() + ok,b = bi.next_one() - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def showNS(self): + def showNS(self): """ Show the content of SALOME naming service """ self.showNScontext(self.rootContext) - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def Resolve(self, Path): - resolve_path=string.split(Path,'/') + def Resolve(self, Path): + resolve_path = string.split(Path,'/') if resolve_path[0] == '': del resolve_path[0] - dir_path=resolve_path[:-1] - context_name=[] + dir_path = resolve_path[:-1] + context_name = [] for e in dir_path: - context_name.append(CosNaming.NameComponent(e,"dir")) + context_name.append(CosNaming.NameComponent(e,"dir")) context_name.append(CosNaming.NameComponent(resolve_path[-1],"object")) try: @@ -136,16 +136,16 @@ class client: obj = None return obj - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def waitNS(self,name,typobj=None,maxcount=240): - count=0 - delta=0.5 + def waitNS(self,name,typobj=None,maxcount=240): + count = 0 + delta = 0.5 print "Searching %s in Naming Service " % name, while(1): count += 1 if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name - obj=self.Resolve(name) + obj = self.Resolve(name) if obj : print " found in %s seconds " % ((count-1)*delta) break @@ -161,42 +161,42 @@ class client: print "%s exists but is not a %s" % (name,typobj) return nobj - if sys.platform != "win32": - def waitNSPID(self, theName, thePID, theTypObj = None): - aCount = 0 - aDelta = 0.5 - anObj = None - print "Searching %s in Naming Service " % theName, - while(1): - try: - os.kill(thePID,0) - except: - raise RuntimeError, "Process %d for %s not found" % (thePID,theName) - aCount += 1 - anObj = self.Resolve(theName) - if anObj: + if sys.platform != "win32": + def waitNSPID(self, theName, thePID, theTypObj = None): + aCount = 0 + aDelta = 0.5 + anObj = None + print "Searching %s in Naming Service " % theName, + while(1): + try: + os.kill(thePID,0) + except: + raise RuntimeError, "Process %d for %s not found" % (thePID,theName) + aCount += 1 + anObj = self.Resolve(theName) + if anObj: print " found in %s seconds " % ((aCount-1)*aDelta) break - else: + else: sys.stdout.write('+') sys.stdout.flush() time.sleep(aDelta) pass - pass - - if theTypObj is None: - return anObj - - anObject = anObj._narrow(theTypObj) - if anObject is None: - print "%s exists but is not a %s" % (theName,theTypObj) - return anObject + pass + + if theTypObj is None: + return anObj + + anObject = anObj._narrow(theTypObj) + if anObject is None: + print "%s exists but is not a %s" % (theName,theTypObj) + return anObject - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def ResolveLogger(self, name): - context_name=[] + def ResolveLogger(self, name): + context_name = [] context_name.append(CosNaming.NameComponent(name,"")) try: @@ -211,16 +211,16 @@ class client: obj = None return obj - # -------------------------------------------------------------------------- + # -------------------------------------------------------------------------- - def waitLogger(self,name,typobj=None,maxcount=40): - count=0 - delta=0.5 + def waitLogger(self,name,typobj=None,maxcount=40): + count = 0 + delta = 0.5 print "Searching %s in Naming Service " % name, while(1): count += 1 if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name - obj=self.ResolveLogger(name) + obj = self.ResolveLogger(name) if obj : print " found in %s seconds " % ((count-1)*delta) break diff --git a/bin/parseConfigFile.py b/bin/parseConfigFile.py index 2f2bbb2ea..212b646a4 100644 --- a/bin/parseConfigFile.py +++ b/bin/parseConfigFile.py @@ -23,7 +23,7 @@ import logging import re from io import StringIO import subprocess -from salomeContextUtils import SalomeContextException +from salomeContextUtils import SalomeContextException #@UnresolvedImport logging.basicConfig() logConfigParser = logging.getLogger(__name__) @@ -133,7 +133,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser): cursect[optname][0] += ','+optval else: cursect[optname] = [optval] - # END OF SUBSITUTION + # END OF SUBSTITUTION else: # valueless option handling cursect[optname] = optval diff --git a/bin/runConsole.py b/bin/runConsole.py index 57c54d0ed..28c3df185 100644 --- a/bin/runConsole.py +++ b/bin/runConsole.py @@ -29,7 +29,7 @@ def __prompt(environment = None, commands=None, message = "Connecting to SALOME" commands = [] import code - import rlcompleter + import rlcompleter #@UnusedImport import readline readline.parse_and_bind("tab: complete") # calling this with globals ensures we can see the environment diff --git a/bin/runSalome.py b/bin/runSalome.py index 0c64fbcd9..da1c56946 100755 --- a/bin/runSalome.py +++ b/bin/runSalome.py @@ -223,10 +223,8 @@ class LoggerServer(Server): def __init__(self,args): self.args=args self.initArgs() - from salome_utils import generateFileName - if sys.platform == "win32": dirpath = os.environ["HOME"] - else: dirpath = "/tmp" - logfile = generateFileName( dirpath, + from salome_utils import generateFileName, getLogDir + logfile = generateFileName( getLogDir(), prefix="logger", extension="log", with_username=True, @@ -489,8 +487,10 @@ def startSalome(args, modules_list, modules_root_dir): # set siman python path before the session server launching to import scripts inside python console if simanStudyName(args): # MPV: use os.environ here because session server is launched in separated process and sys.path is missed in this case - os.environ["PYTHONPATH"] = "/tmp/SimanSalome/" + args['siman_study'] + "/" + \ - args['siman_scenario'] + "/" + args['siman_user'] + os.pathsep + os.environ["PYTHONPATH"]; + from salome_utils import getTmpDir + ppath = os.path.join(getTmpDir, "SimanSalome", args['siman_study'], + args['siman_scenario'], args['siman_user']) + os.environ["PYTHONPATH"] = ppath + os.pathsep + os.environ["PYTHONPATH"] # Launch Session Server (to show splash ASAP) # @@ -771,11 +771,8 @@ def registerEnv(args, modules_list, modules_root_dir): Register args, modules_list, modules_root_dir in a file for further use, when SALOME is launched embedded in an other application. """ - if sys.platform == "win32": - fileEnv = os.getenv('TEMP') - else: - fileEnv = '/tmp/' - + from salome_utils import getTmpDir + fileEnv = getTmpDir() fileEnv += os.getenv('USER') + "_" + str(args['port']) \ + '_' + args['appname'].upper() + '_env' fenv=open(fileEnv,'w') diff --git a/bin/salomeContext.py b/bin/salomeContext.py index bcf54f562..51e0c51a9 100644 --- a/bin/salomeContext.py +++ b/bin/salomeContext.py @@ -36,19 +36,31 @@ def usage(): #exeName = os.path.splitext(os.path.basename(__file__))[0] msg = '''\ -Usage: salome [command] [options] [--config=file1,...,filen] +Usage: salome [command] [options] [--config=] Commands: - start Launches SALOME virtual application [DEFAULT] - shell Executes a script under SALOME application environment +========= + start Starts a SALOME session (through virtual application) + shell Initializes SALOME environment, and executes scripts passed + as command arguments connect Connects a Python console to the active SALOME session - killall Kill all SALOME running sessions + killall Kill all SALOME running sessions for current user info Display some information about SALOME help Show this message - coffee Yes! SALOME can also make coffee!!" + coffee Yes! SALOME can also make coffee!! -Use salome start --help or salome shell --help -to show help on start and shell commands. +If no command is given, default to start. + +Command options: +================ + Use salome --help to show help on command ; available for start + and shell commands. + +--config= +========================== + Initialize SALOME environment from a list of context files and/or a list + of folders containing context files. The list is comma-separated, whithout + any blank characters. ''' print msg @@ -106,8 +118,10 @@ class SalomeContext: # kill = True # args.remove(e) + import os absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','') - proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), pickle.dumps(self), pickle.dumps(args)], shell=False, close_fds=True) + env_copy = os.environ.copy() + proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), pickle.dumps(self), pickle.dumps(args)], shell=False, close_fds=True, env=env_copy) msg = proc.communicate() # if kill: # self._killAll(args) @@ -203,6 +217,16 @@ class SalomeContext: See usage for details on commands. """ def _startSalome(self, args): + try: + import os + absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH') + import sys + path = os.path.join(absoluteAppliPath, "bin", "salome") + if not path in sys.path: + sys.path[:0] = [path] + except: + pass + command, options = self.__parseArguments(args) sys.argv = options diff --git a/bin/salomeContextUtils.py.in b/bin/salomeContextUtils.py.in index 3ff44603e..dedf40565 100644 --- a/bin/salomeContextUtils.py.in +++ b/bin/salomeContextUtils.py.in @@ -92,6 +92,10 @@ def getConfigFileNames(args, checkExistence=False): # def __getScriptPath(scriptName, searchPathList): + scriptName = os.path.expanduser(scriptName) + if os.path.isabs(scriptName): + return scriptName + if searchPathList is None or len(searchPathList) == 0: return None @@ -111,6 +115,13 @@ class ScriptAndArgs: self.script = script self.args = args self.out = out + # + def __repr__(self): + msg = "\n# Script: %s\n"%self.script + msg += " * Input: %s\n"%self.args + msg += " * Output: %s\n"%self.out + return msg + # # class ScriptAndArgsObjectEncoder(json.JSONEncoder): def default(self, obj): @@ -139,13 +150,14 @@ def getScriptsAndArgs(args=None, searchPathList=None): currentScript = None for i in range(len(args)): - elt = args[i] + elt = os.path.expanduser(args[i]) + isDriver = (elt == "driver") # special case for YACS scheme execution if elt.startswith(argsPrefix): if not currentKey or callPython: raise SalomeContextException("args list must follow corresponding script file in command line.") elt = elt.replace(argsPrefix, '') - scriptArgs[len(scriptArgs)-1].args = elt.split(",") + scriptArgs[len(scriptArgs)-1].args = [os.path.expanduser(x) for x in elt.split(",")] currentKey = None callPython = False afterArgs = True @@ -153,7 +165,7 @@ def getScriptsAndArgs(args=None, searchPathList=None): if (not currentKey and not afterArgs) or callPython: raise SalomeContextException("out list must follow both corresponding script file and its args in command line.") elt = elt.replace(outPrefix, '') - scriptArgs[len(scriptArgs)-1].out = elt.split(",") + scriptArgs[len(scriptArgs)-1].out = [os.path.expanduser(x) for x in elt.split(",")] currentKey = None callPython = False afterArgs = False @@ -170,19 +182,24 @@ def getScriptsAndArgs(args=None, searchPathList=None): elt = eltInSearchPath if elt[-4:] != ".hdf": - if elt[-3:] == ".py": + if elt[-3:] == ".py" or isDriver: currentScript = os.path.abspath(elt) elif os.path.isfile(elt+".py"): currentScript = os.path.abspath(elt+".py") else: currentScript = os.path.abspath(elt) # python script not necessary has .py extension pass + if currentScript and callPython: currentKey = "@PYTHONBIN@ "+currentScript scriptArgs.append(ScriptAndArgs(script=currentKey)) callPython = False elif currentScript: - if not os.access(currentScript, os.X_OK): + if isDriver: + currentKey = currentScript + scriptArgs.append(ScriptAndArgs(script=currentKey)) + callPython = False + elif not os.access(currentScript, os.X_OK): currentKey = "@PYTHONBIN@ "+currentScript scriptArgs.append(ScriptAndArgs(script=currentKey)) else: diff --git a/bin/salome_utils.py b/bin/salome_utils.py index a27009a45..43ffaba7c 100644 --- a/bin/salome_utils.py +++ b/bin/salome_utils.py @@ -39,6 +39,7 @@ __all__ = [ 'getShortHostName', 'getAppName', 'getPortNumber', + 'getLogDir', 'getTmpDir', 'getHomeDir', 'generateFileName', @@ -71,7 +72,7 @@ def getORBcfgInfo(): """ Get omniORB current configuration. Returns a list of three values: [ orb_version, host_name, port_number ]. - + The information is retrieved from the omniORB configuration file defined by the OMNIORB_CONFIG environment variable. If omniORB configuration file can not be accessed, a list of three empty @@ -125,12 +126,14 @@ def getPortFromORBcfg(): def getUserName(): """ Get user name: - 1. try USER environment variable + 1. try USER environment variable (USERNAME on windows) 2. if fails, return 'unknown' as default user name """ - import os - return os.getenv( "USER", "unknown" ) # 'unknown' is default user name - + import os, sys + if sys.platform == "win32": + return os.getenv("USERNAME", "unknown") + else: + return os.getenv("USER", "unknown") # --- def getHostName(): @@ -168,7 +171,7 @@ def getShortHostName(): except: pass return "unknown" # 'unknown' is default host name - + # --- def getAppName(): @@ -208,41 +211,27 @@ def getHomeDir(): """ Get home directory. """ - import os, sys - if sys.platform == "win32": - # for Windows the home directory is detected in the following way: - # 1. try USERPROFILE env variable - # 2. try combination of HOMEDRIVE and HOMEPATH env variables - # 3. try HOME env variable - # TODO: on Windows, also GetUserProfileDirectoryW() system function might be used - dir = os.getenv("USERPROFILE") - if not dir and os.getenv("HOMEDRIVE") and os.getenv("HOMEPATH"): - dir = os.path.join(os.getenv("HOMEDRIVE"), os.getenv("HOMEPATH")) - if not dir: - dir = os.getenv("HOME") - pass - else: - # for Linux: use HOME variable - dir = os.getenv("HOME") - pass - return dir + import os + return os.path.realpath(os.path.expanduser('~')) +# --- + +def getLogDir(): + """ + Get directory to be used for the log files. + """ + import os + return os.path.join(getTmpDir(), "logs", getUserName()) # --- def getTmpDir(): """ Get directory to be used for the temporary files. """ - import os, sys - if sys.platform == "win32": - # for Windows: temporarily using home directory for tmp files; - # to be replaced with TEMP environment variable later... - dir = os.getenv("HOME") - else: - # for Linux: use /tmp/logs/{user} folder - dir = os.path.join( '/tmp', 'logs', getUserName() ) - pass - return dir - + import os, tempfile + f = tempfile.NamedTemporaryFile() + tmpdir = os.path.dirname(f.name) + f.close() + return tmpdir # --- def generateFileName( dir, prefix = None, suffix = None, extension = None, @@ -481,6 +470,7 @@ def verbose(): pass # return _verbose +# -- def setVerbose(level): """ @@ -489,4 +479,4 @@ def setVerbose(level): global _verbose _verbose = level return - +# -- diff --git a/bin/setenv.py b/bin/setenv.py index cb5c8d8d0..e302fd1dd 100755 --- a/bin/setenv.py +++ b/bin/setenv.py @@ -81,12 +81,12 @@ def get_lib_dir(): def get_config(silent=False): """ Get list of modules, paths. - + Read args from launch configure xml file and command line options. Check variables _ROOT_DIR and set list of used modules. - Return args, modules_list, modules_root_dir + Return args, modules_list, modules_root_dir """ - + # read args from launch configure xml file and command line options #*** Test additional option @@ -150,14 +150,14 @@ def get_config(silent=False): def set_env(args, modules_list, modules_root_dir, silent=False): """Add to the PATH-variables modules specific paths""" - + import os - from salome_utils import getTmpDir, generateFileName, makeTmpDir, getPortNumber + from salome_utils import getLogDir, generateFileName, makeTmpDir, getPortNumber # create temporary directory for environment files needed by modules from the list port = getPortNumber(False) if port: - tmp_dir = getTmpDir() + tmp_dir = getLogDir() env_dir = generateFileName(tmp_dir, prefix="env", with_port=True) makeTmpDir(env_dir) pass @@ -167,8 +167,8 @@ def set_env(args, modules_list, modules_root_dir, silent=False): if os.getenv('SALOME_BATCH') == None: os.putenv('SALOME_BATCH','0') if args["gui"] : - modules_list = modules_list[:] + ["GUI"] - modules_list = modules_list[:] + ["KERNEL"] + modules_list = modules_list[:] + ["GUI"] + modules_list = modules_list[:] + ["KERNEL"] for module in modules_list : if modules_root_dir.has_key(module): module_root_dir = modules_root_dir[module] @@ -224,9 +224,9 @@ def set_env(args, modules_list, modules_root_dir, silent=False): os.environ["SALOMEPATH"]=";".join(modules_root_dir_list) else: os.environ["SALOMEPATH"]=":".join(modules_root_dir_list) - + # set trace environment variable - + if not os.environ.has_key("SALOME_trace"): os.environ["SALOME_trace"]="local" if args['file']: