Salome HOME
EDF bug 17743, salome.sg regressions in DEV (missing getAllSelected method)
[modules/kernel.git] / bin / runSalome.py
index c56da55cfad7cfb034187ece4484655605b2e515..3aa96b0927c2cabe72c8100eaa10598b31126a90 100755 (executable)
@@ -1,6 +1,6 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
 #
 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
@@ -8,7 +8,7 @@
 # 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.
+# version 2.1 of the License, or (at your option) any later version.
 #
 # This library is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -31,11 +31,9 @@ import orbmodule
 import setenv
 from launchConfigureParser import verbose
 from server import process_id, Server
-
-if sys.platform == "win32":
-    SEP = ";"
-else:
-    SEP = ":"
+import json
+import subprocess
+from salomeContextUtils import ScriptAndArgsObjectEncoder
 
 # -----------------------------------------------------------------------------
 
@@ -43,31 +41,31 @@ from killSalome import killAllPorts
 
 def killLocalPort():
     """
-    kill servers from a previous SALOME exection, if needed,
+    kill servers from a previous SALOME execution, if needed,
     on the CORBA port given in args of runSalome
     """
-    
+
     from killSalomeWithPort import killMyPort
     my_port=str(args['port'])
     try:
         killMyPort(my_port)
     except:
-        print "problem in killLocalPort()"
+        print("problem in killLocalPort()")
         pass
     pass
-    
+
 def givenPortKill(port):
     """
-    kill servers from a previous SALOME exection, if needed,
+    kill servers from a previous SALOME execution, if needed,
     on the same CORBA port
     """
-    
+
     from killSalomeWithPort import killMyPort
     my_port=port
     try:
         killMyPort(my_port)
     except:
-        print "problem in LocalPortKill(), killMyPort("<<port<<")"
+        print("problem in LocalPortKill(), killMyPort(%s)"%port)
         pass
     pass
 
@@ -91,21 +89,21 @@ def kill_salome(args):
 class InterpServer(Server):
     def __init__(self,args):
         self.args=args
-        if sys.platform != "win32":
-          env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
-          self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
-        else:
+        if sys.platform == "win32":
           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
-       
+        elif sys.platform == "darwin":
+          env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
+        else:
+          env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
+
     def run(self):
         global process_id
         command = self.CMD
-        print "INTERPSERVER::command = ", command
-        if sys.platform == "win32":
-          import win32pm
-          pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
-        else:
-          pid = os.spawnvp(os.P_NOWAIT, command[0], command)
+        print("INTERPSERVER::command = ", command)
+        import subprocess
+        pid = subprocess.Popen(command).pid
         process_id[pid]=self.CMD
         self.PID = pid
 
@@ -118,7 +116,7 @@ def get_cata_path(list_modules,modules_root_dir):
     cata_path=[]
 
     for module in list_modules:
-        if modules_root_dir.has_key(module):
+        if module in modules_root_dir:
             module_root_dir=modules_root_dir[module]
             module_cata=module+"Catalog.xml"
             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
@@ -132,18 +130,16 @@ def get_cata_path(list_modules,modules_root_dir):
                     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]
-                if not modules_cata.has_key(module_name):
+                if module_name not in modules_cata:
                     cata_path.append(cata_file)
                     modules_cata[module_name]=cata_file
 
     return cata_path
 
-
-
 class CatalogServer(Server):
     def __init__(self,args):
         self.args=args
@@ -152,7 +148,7 @@ class CatalogServer(Server):
         self.SCMD2=[]
         home_dir=os.getenv('HOME')
         if home_dir is not None:
-            self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
+            self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
 
     def setpath(self,modules_list,modules_root_dir):
         list_modules = modules_list[:]
@@ -164,7 +160,7 @@ class CatalogServer(Server):
 
         cata_path=get_cata_path(list_modules,modules_root_dir)
 
-        self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+        self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
 
 # ---
 
@@ -193,21 +189,18 @@ class RegistryServer(Server):
 # ---
 
 class ContainerCPPServer(Server):
-    def __init__(self,args):
+    def __init__(self,args,with_gui=False):
         self.args=args
         self.initArgs()
         self.CMD=['SALOME_Container','FactoryServer']
-
-# ---
-
-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']
+        if not with_gui and self.args["valgrind_session"]:
+            l = ["valgrind"]
+            val = os.getenv("VALGRIND_OPTIONS")
+            if val:
+                l += val.split()
+                pass
+            self.CMD = l + self.CMD
+            pass
 
 # ---
 
@@ -215,19 +208,17 @@ 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,
                                     with_hostname=True,
                                     with_port=True)
-        print "==========================================================="
-        print "Logger server: put log to the file:"
-        print logfile
-        print "==========================================================="
+        print("===========================================================")
+        print("Logger server: put log to the file:")
+        print(logfile)
+        print("===========================================================")
         self.CMD=['SALOME_Logger_Server', logfile]
         pass
     pass # end of LoggerServer class
@@ -250,7 +241,7 @@ class SessionServer(Server):
             self.SCMD1+=['--with','ModuleCatalog','(','-common']
             home_dir=os.getenv('HOME')
             if home_dir is not None:
-                self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
+                self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
             self.SCMD2+=[')']
         if 'study' in self.args['embedded']:
             self.SCMD2+=['--with','SALOMEDS','(',')']
@@ -258,14 +249,14 @@ class SessionServer(Server):
             self.SCMD2+=['--with','Container','(','FactoryServer',')']
         if 'SalomeAppEngine' in self.args['embedded']:
             self.SCMD2+=['--with','SalomeAppEngine','(',')']
-            
+
         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 'session_gui' in self.args:
                 session_gui = self.args['session_gui']
             if session_gui:
                 self.SCMD2+=['GUI']
@@ -276,12 +267,17 @@ class SessionServer(Server):
                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
                     pass
                 pass
+                if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
+                    msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
+                    self.SCMD2+=['--pyscript=%s'%(msg)]
+                    pass
+                pass
             pass
         if self.args['noexcepthandler']:
             self.SCMD2+=['noexcepthandler']
-        if self.args.has_key('user_config'):
+        if 'user_config' in self.args:
             self.SCMD2+=['--resources=%s'%self.args['user_config']]
-        if self.args.has_key('modules'):
+        if 'modules' in self.args:
             list_modules = []
             #keep only modules with GUI
             for m in modules_list:
@@ -294,9 +290,10 @@ class SessionServer(Server):
                   list_modules.insert(0,m)
             list_modules.reverse()
             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
-
-        if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
-            self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
+            pass
+        if 'language' in self.args:
+            self.SCMD2+=['--language=%s' % self.args['language']]
+        pass
 
     def setpath(self,modules_list,modules_root_dir):
         list_modules = modules_list[:]
@@ -308,14 +305,14 @@ class SessionServer(Server):
 
         cata_path=get_cata_path(list_modules,modules_root_dir)
 
-        if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
+        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
-        if self.args.has_key('test'):
+        if 'test' in self.args:
             self.CMD+=['-test'] + self.args['test']
-        elif self.args.has_key('play'):
+        elif 'play' in self.args:
             self.CMD+=['-play'] + self.args['play']
 
         if self.args["gdb_session"] or self.args["ddd_session"]:
@@ -333,7 +330,7 @@ class SessionServer(Server):
                 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
                 pass
             pass
-        
+
         if self.args["valgrind_session"]:
             l = ["valgrind"]
             val = os.getenv("VALGRIND_OPTIONS")
@@ -342,7 +339,7 @@ class SessionServer(Server):
                 pass
             self.CMD = l + self.CMD
             pass
-        
+
 # ---
 
 class LauncherServer(Server):
@@ -374,26 +371,11 @@ class LauncherServer(Server):
 
         cata_path=get_cata_path(list_modules,modules_root_dir)
 
-        if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
+        if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+            self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
-
-class NotifyServer(Server):
-    def __init__(self,args,modules_root_dir):
-        self.args=args
-        self.initArgs()
-        self.modules_root_dir=modules_root_dir
-        myLogName = os.environ["LOGNAME"]
-        self.CMD=['notifd','-c',
-                  self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
-                  '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
-                  '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
-                  '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
-                  '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
-                  ]
-
 #
 # -----------------------------------------------------------------------------
 
@@ -406,35 +388,33 @@ def startGUI(clt):
     import SALOME_Session_idl
     session=clt.waitNS("/Kernel/Session",SALOME.Session)
     session.GetInterface()
-  
+
 # -----------------------------------------------------------------------------
 
 def startSalome(args, modules_list, modules_root_dir):
     """Launch all SALOME servers requested by args"""
     init_time = os.times()
 
-    if verbose(): print "startSalome ", args
-    
+    if verbose(): print("startSalome ", args)
+
     #
     # Set server launch command
     #
-    if args.has_key('server_launch_mode'):
+    if 'server_launch_mode' in args:
         Server.set_server_launch_mode(args['server_launch_mode'])
-    
+
     #
     # Wake up session option
     #
     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,
@@ -442,11 +422,11 @@ def startSalome(args, modules_list, modules_root_dir):
             os.environ['OMNIORB_CONFIG'] = last_running_config
             pass
         pass
-    
+
     #
     # Initialisation ORB and Naming Service
     #
-   
+
     clt=orbmodule.client(args)
 
     #
@@ -478,18 +458,6 @@ def startSalome(args, modules_list, modules_root_dir):
         session.GetInterface()
         args["session_object"] = session
         return clt
-    
-    # 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"])
-      f = open(file_name, "w")
-      f.write(os.environ['NSPORT'])
-      f.close()
 
     # Launch Logger Server (optional)
     # and wait until it is registered in naming service
@@ -500,15 +468,6 @@ def startSalome(args, modules_list, modules_root_dir):
         myServer.run()
         clt.waitLogger("Logger")
 
-    # Notify Server launch
-    #
-
-    if sys.platform != "win32":
-      if verbose(): print "Notify Server to launch"
-    
-      myServer=NotifyServer(args,modules_root_dir)
-      myServer.run()
-
     # Launch  Session Server (to show splash ASAP)
     #
 
@@ -550,20 +509,20 @@ def startSalome(args, modules_list, modules_root_dir):
     # and wait until it is registered in naming service
     #
 
-    #print "ARGS = ",args
+    # print("ARGS = ",args)
     if ('study' not in args['embedded']) | (args["gui"] == 0):
-        print "RunStudy"
+        print("RunStudy")
         myServer=SalomeDSServer(args)
         myServer.run()
         if sys.platform == "win32":
-          clt.waitNS("/myStudyManager")
+          clt.waitNS("/Study")
         else:
-          clt.waitNSPID("/myStudyManager",myServer.PID)
+          clt.waitNSPID("/Study",myServer.PID)
 
     #
     # Launch LauncherServer
     #
-    
+
     myCmServer = LauncherServer(args)
     myCmServer.setpath(modules_list,modules_root_dir)
     myCmServer.run()
@@ -577,7 +536,7 @@ def startSalome(args, modules_list, modules_root_dir):
 
 
     from Utils_Identity import getShortHostName
-    
+
     if os.getenv("HOSTNAME") == None:
         if os.getenv("HOST") == None:
             os.environ["HOSTNAME"]=getShortHostName()
@@ -585,39 +544,29 @@ def startSalome(args, modules_list, modules_root_dir):
             os.environ["HOSTNAME"]=os.getenv("HOST")
 
     theComputer = getShortHostName()
-    
+
     #
     # Launch local C++ Container (FactoryServer),
     # and wait until it is registered in naming service
     #
 
-    if ('cppContainer' in args['standalone']) | (args["gui"] == 0) : 
-        myServer=ContainerCPPServer(args)
+    if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
+        myServer=ContainerCPPServer(args, with_gui=args["gui"]!=0)
         myServer.run()
         if sys.platform == "win32":
           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
         else:
           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
 
-    #
-    # Launch local Python Container (FactoryServerPy),
-    # and wait until it is registered in naming service
-    #
-
     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
     #
-    
+
     if args["gui"]:
-##----------------        
+##----------------
         import Engines
         import SALOME
         import SALOMEDS
@@ -629,33 +578,33 @@ def startSalome(args, modules_list, modules_root_dir):
           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
         args["session_object"] = session
     end_time = os.times()
-    if verbose(): print
-    print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
-                                                         - init_time[4])
+    if verbose(): print()
+    print("Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
+                                                         - init_time[4]))
 
     # ASV start GUI without Loader
     #if args['gui']:
     #    session.GetInterface()
 
     #
-    # additionnal external python interpreters
+    # additional external python interpreters
     #
     nbaddi=0
-    
+
     try:
         if 'interp' in args:
             nbaddi = args['interp']
     except:
         import traceback
         traceback.print_exc()
-        print "-------------------------------------------------------------"
-        print "-- to get an external python interpreter:runSalome --interp=1"
-        print "-------------------------------------------------------------"
-        
-    if verbose(): print "additional external python interpreters: ", nbaddi
+        print("-------------------------------------------------------------")
+        print("-- to get an external python interpreter:runSalome --interp=1")
+        print("-------------------------------------------------------------")
+
+    if verbose(): print("additional external python interpreters: ", nbaddi)
     if nbaddi:
         for i in range(nbaddi):
-            print "i=",i
+            print("i=",i)
             anInterp=InterpServer(args)
             anInterp.run()
 
@@ -666,7 +615,7 @@ def startSalome(args, modules_list, modules_root_dir):
             import readline
         except ImportError:
             pass
-        
+
     return clt
 
 # -----------------------------------------------------------------------------
@@ -678,52 +627,52 @@ def useSalome(args, modules_list, modules_root_dir):
     show registered objects in Naming Service.
     """
     global process_id
-    
+
     clt=None
     try:
         clt = startSalome(args, modules_list, modules_root_dir)
     except:
         import traceback
         traceback.print_exc()
-        print
-        print
-        print "--- Error during Salome launch ---"
-        
-    #print process_id
+        print()
+        print()
+        print("--- Error during Salome launch ---")
+
+    # print(process_id)
 
     from addToKillList import addToKillList
     from killSalomeWithPort import getPiDict
 
     filedict = getPiDict(args['port'])
-    for pid, cmd in process_id.items():
+    for pid, cmd in list(process_id.items()):
         addToKillList(pid, cmd, args['port'])
         pass
 
-    if verbose(): print """
+    if verbose(): print("""
     Saving of the dictionary of Salome processes in %s
     To kill SALOME processes from a console (kill all sessions from all ports):
-      python killSalome.py 
+      python killSalome.py
     To kill SALOME from the present interpreter, if it is not closed :
       killLocalPort()      --> kill this session
                                (use CORBA port from args of runSalome)
-      givenPortKill(port)  --> kill a specific session with given CORBA port 
+      givenPortKill(port)  --> kill a specific session with given CORBA port
       killAllPorts()       --> kill all sessions
-    
+
     runSalome, with --killall option, starts with killing
     the processes resulting from the previous execution.
-    """%filedict
-    
+    """%filedict)
+
     #
     #  Print Naming Service directory list
     #
-    
+
     if clt != None:
         if verbose():
-            print
-            print " --- registered objects tree in Naming Service ---"
+            print()
+            print(" --- registered objects tree in Naming Service ---")
             clt.showNS()
             pass
-        
+
         if not args['gui'] or not args['session_gui']:
             if args['shutdown_servers']:
                 class __utils__(object):
@@ -736,56 +685,38 @@ def useSalome(args, modules_list, modules_root_dir):
                         self.killSalomeWithPort.killMyPort(self.port)
                         return
                     pass
-                args['shutdown_servers'] = __utils__(args['port'])
+                def func(s):
+                    del s
+                import atexit
+                atexit.register(func, __utils__(args['port']))
                 pass
             pass
-        
-        # run python scripts, passed via --execute option
+
+        # run python scripts, passed as command line arguments
         toimport = []
-        if args.has_key('pyscript'):
-            if args.has_key('gui') and args.has_key('session_gui'):
-                if not args['gui'] or not args['session_gui']:
+        if 'gui' in args and 'session_gui' in args:
+            if not args['gui'] or not args['session_gui']:
+                if 'study_hdf' in args:
+                    toopen = args['study_hdf']
+                    if toopen:
+                        import salome
+                        salome.salome_init(path=toopen)
+                if 'pyscript' in args:
                     toimport = args['pyscript']
+        from salomeContextUtils import formatScriptsAndArgs
+        command = formatScriptsAndArgs(toimport)
+        if command:
+            proc = subprocess.Popen(command, shell=True)
+            addToKillList(proc.pid, command, args['port'])
+            res = proc.wait()
+            if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
 
-        for srcname in toimport :
-            if srcname == 'killall':
-                clt.showNS()
-                killAllPorts()
-                sys.exit(0)
-            else:
-                if os.path.isabs(srcname):
-                    if os.path.exists(srcname):
-                        execScript(srcname)
-                    elif os.path.exists(srcname+".py"):
-                        execScript(srcname+".py")
-                    else:
-                        print "Can't execute file %s" % srcname
-                    pass
-                else:
-                    found = False
-                    for path in [os.getcwd()] + sys.path:
-                        if os.path.exists(os.path.join(path,srcname)):
-                            execScript(os.path.join(path,srcname))
-                            found = True
-                            break
-                        elif os.path.exists(os.path.join(path,srcname+".py")):
-                            execScript(os.path.join(path,srcname+".py"))
-                            found = True
-                            break
-                        pass
-                    if not found:
-                        print "Can't execute file %s" % srcname
-                        pass
-                    pass
-                pass
-            pass
-        pass
     return clt
-    
+
 def execScript(script_path):
-    print 'executing', script_path
-    sys.path.insert(0, os.path.dirname(script_path))
-    execfile(script_path,globals())
+    print('executing', script_path)
+    sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
+    exec(compile(open(script_path).read(), script_path, 'exec'),globals())
     del sys.path[0]
 
 # -----------------------------------------------------------------------------
@@ -795,12 +726,10 @@ 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/'
-
-    fileEnv += os.getenv('USER') + "_" + str(args['port']) \
+    from salome_utils import getTmpDir
+    fileEnv = getTmpDir()
+    from salome_utils import getUserName
+    fileEnv += getUserName() + "_" + str(args['port']) \
             + '_' + args['appname'].upper() + '_env'
     fenv=open(fileEnv,'w')
     pickle.dump((args, modules_list, modules_root_dir),fenv)
@@ -809,112 +738,6 @@ def registerEnv(args, modules_list, modules_root_dir):
 
 # -----------------------------------------------------------------------------
 
-def searchFreePort(args, save_config=1):
-    print "Searching for a free port for naming service:",
-    #
-    if sys.platform == "win32":
-        tmp_file = os.getenv('TEMP');
-    else:
-        tmp_file = '/tmp'
-    tmp_file = os.path.join(tmp_file, '.netstat_%s'%os.getpid())
-    #
-    ###status = os.system("netstat -ltn | grep -E :%s > /dev/null 2>&1"%(NSPORT))
-    os.system( "netstat -a -n > %s" % tmp_file );
-    f = open( tmp_file, 'r' );
-    ports = f.readlines();
-    f.close();
-    os.remove( tmp_file );
-    #
-    def portIsUsed(port, data):
-        regObj = re.compile( ".*tcp.*:([0-9]+).*:.*listen", re.IGNORECASE );
-        for item in data:
-            try:
-                p = int(regObj.match(item).group(1))
-                if p == port: return True
-                pass
-            except:
-                pass
-            pass
-        return False
-    #
-    NSPORT=2810
-    limit=NSPORT+100
-    #
-    while 1:
-        if not portIsUsed(NSPORT, ports):
-            print "%s - OK"%(NSPORT)
-            #
-            from salome_utils import generateFileName, getHostName
-            hostname = getHostName()
-            #
-            home  = os.getenv("HOME")
-            appli = os.getenv("APPLI")
-            kwargs={}
-            if appli is not None: 
-              home = os.path.join(os.path.realpath(home), appli,"USERS")
-              kwargs["with_username"]=True
-            #
-            omniorb_config = generateFileName(home, prefix="omniORB",
-                                              extension="cfg",
-                                              hidden=True,
-                                              with_hostname=True,
-                                              with_port=NSPORT,
-                                              **kwargs)
-            orbdata = []
-            initref = "NameService=corbaname::%s:%s"%(hostname, NSPORT)
-            from omniORB import CORBA
-            if CORBA.ORB_ID == "omniORB4":
-                orbdata.append("InitRef = %s"%(initref))
-                orbdata.append("giopMaxMsgSize = 2097152000  # 2 GBytes")
-                orbdata.append("traceLevel = 0 # critical errors only")
-            else:
-                orbdata.append("ORBInitRef %s"%(initref))
-                orbdata.append("ORBgiopMaxMsgSize = 2097152000  # 2 GBytes")
-                orbdata.append("ORBtraceLevel = 0 # critical errors only")
-                pass
-            orbdata.append("")
-            f = open(omniorb_config, "w")
-            f.write("\n".join(orbdata))
-            f.close()
-            #
-            os.environ['OMNIORB_CONFIG'] = omniorb_config
-            os.environ['NSPORT'] = "%s"%(NSPORT)
-            os.environ['NSHOST'] = "%s"%(hostname)
-            args['port'] = os.environ['NSPORT']
-            #
-            if save_config:
-                last_running_config = generateFileName(home, prefix="omniORB",
-                                                       suffix="last",
-                                                       extension="cfg",
-                                                       hidden=True,
-                                                       **kwargs)
-                try:
-                    if sys.platform == "win32":
-                        import shutil       
-                        shutil.copyfile(omniorb_config, last_running_config)
-                    else:
-                        try:
-                            os.remove(last_running_config)
-                        except OSError:
-                            pass
-                        os.symlink(omniorb_config, last_running_config)
-                        pass
-                    pass
-                except:
-                    pass
-            break
-        print "%s"%(NSPORT),
-        if NSPORT == limit:
-            msg  = "\n"
-            msg += "Can't find a free port to launch omniNames\n"
-            msg += "Try to kill the running servers and then launch SALOME again.\n"
-            raise RuntimeError, msg
-        NSPORT=NSPORT+1
-        pass
-    return
-    
-# -----------------------------------------------------------------------------
-
 def no_main():
     """Salome Launch, when embedded in other application"""
     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
@@ -922,20 +745,31 @@ def no_main():
     args, modules_list, modules_root_dir = pickle.load(fenv)
     fenv.close()
     kill_salome(args)
+    from searchFreePort import searchFreePort
     searchFreePort(args, 0)
     clt = useSalome(args, modules_list, modules_root_dir)
     return clt
 
 # -----------------------------------------------------------------------------
 
-def main():
+def main(exeName=None):
     """Salome launch as a main application"""
+
+    # define folder to store omniorb config (initially in virtual application folder)
+    try:
+        from salomeContextUtils import setOmniOrbUserPath
+        setOmniOrbUserPath()
+    except Exception as e:
+        print(e)
+        sys.exit(1)
+
     from salome_utils import getHostName
-    print "runSalome running on %s" % getHostName()
-    args, modules_list, modules_root_dir = setenv.get_config()
+    args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName)
+    print("runSalome running on %s" % getHostName())
+
     kill_salome(args)
     save_config = True
-    if args.has_key('save_config'):
+    if 'save_config' in args:
         save_config = args['save_config']
     # --
     test = True
@@ -943,7 +777,8 @@ def main():
         test = False
         pass
     if test:
-        searchFreePort(args, save_config)
+        from searchFreePort import searchFreePort
+        searchFreePort(args, save_config, args.get('useport'))
         pass
     # --
     #setenv.main()
@@ -992,7 +827,7 @@ def foreGround(clt, args):
       server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
     else:
       server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
-    server.run()   
+    server.run()
     # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
     # --
     dt = 1.0
@@ -1012,17 +847,15 @@ def foreGround(clt, args):
         killMyPort(port)
         pass
     return
+#
 
-# -----------------------------------------------------------------------------
-
-if __name__ == "__main__":
-    import user
+def runSalome():
     clt,args = main()
     # --
     test = args['gui'] and args['session_gui']
     test = test or args['wake_up_session']
     # --
-    # The next test covers the --pinter option or var PYTHONINSPECT setted
+    # The next test covers the --pinter option or if var PYTHONINSPECT is set
     # --
     test = test and not os.environ.get('PYTHONINSPECT')
     # --
@@ -1041,5 +874,11 @@ if __name__ == "__main__":
     if test:
         foreGround(clt, args)
         pass
-    # --
     pass
+#
+
+# -----------------------------------------------------------------------------
+
+if __name__ == "__main__":
+    runSalome()
+#