Salome HOME
Fix the following problems:
[modules/kernel.git] / bin / salomeRunner.py
index 875e914d8a36ff12ebb8d304e6303069980236b2..aa1dee6cafbf41b3de61f3c98a7ac38dbec8eb35 100644 (file)
@@ -14,6 +14,28 @@ import platform
 from salomeLauncherUtils import SalomeRunnerException
 from salomeLauncherUtils import getScriptsAndArgs, formatScriptsAndArgs
 
+def usage():
+  #exeName = os.path.splitext(os.path.basename(__file__))[0]
+
+  msg = '''\
+Usage: salome [command] [options] [--config=file1,...,filen]
+
+Commands:
+    start         Launches SALOME virtual application [DEFAULT]
+    shell         Executes a script under SALOME application environment
+    connect       Connects a Python console to the active SALOME session
+    killall       Kill all SALOME running sessions
+    info          Display some information about SALOME
+    help          Show this message
+    coffee        Yes! SALOME can also make coffee!!"
+
+Use salome start --help or salome shell --help
+to show help on start and shell commands.
+'''
+
+  print msg
+#
+
 """
 The SalomeRunner class in an API to configure SALOME environment then
 start SALOME using a single python command.
@@ -36,17 +58,18 @@ class SalomeRunner:
     if len(configFileNames) == 0:
       raise SalomeRunnerException("No configuration files given")
 
+    reserved=['PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'MANPATH', 'PV_PLUGIN_PATH']
     for filename in configFileNames:
       basename, extension = os.path.splitext(filename)
       if extension == ".cfg":
-        self.__setEnvironmentFromConfigFile(filename)
+        self.__setEnvironmentFromConfigFile(filename, reserved)
       elif extension == ".sh":
         #new convert procedures, temporary could be use not to be automatically deleted
         #temp = tempfile.NamedTemporaryFile(suffix='.cfg', delete=False)
         temp = tempfile.NamedTemporaryFile(suffix='.cfg')
         try:
-          convertEnvFileToConfigFile(filename, temp.name)
-          self.__setEnvironmentFromConfigFile(temp.name)
+          convertEnvFileToConfigFile(filename, temp.name, reserved)
+          self.__setEnvironmentFromConfigFile(temp.name, reserved)
         except ConfigParser.ParsingError, e:
           self.getLogger().warning("Invalid token found when parsing file: %s\n"%(filename))
           print e
@@ -62,33 +85,23 @@ class SalomeRunner:
     # Run this module as a script, in order to use appropriate Python interpreter
     # according to current path (initialized from environment files).
     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()
+    proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeRunner.py"), pickle.dumps(self),  pickle.dumps(args)], shell=False, close_fds=True)
+    proc.communicate()
   #
 
   """Append value to PATH environment variable"""
   def addToPath(self, value):
-    self.__addToReserved('PATH', value)
+    self.addToEnviron('PATH', value)
   #
 
   """Append value to LD_LIBRARY_PATH environment variable"""
   def addToLdLibraryPath(self, value):
-    self.__addToReserved('LD_LIBRARY_PATH', value)
+    self.addToEnviron('LD_LIBRARY_PATH', value)
   #
 
   """Append value to PYTHONPATH environment variable"""
   def addToPythonPath(self, value):
-    self.__addToReserved('PYTHONPATH', value)
-  #
-
-  """Append value to TCLLIBPATH environment variable"""
-  def addToTclLibPath(self, value):
-    self.__addToReservedTclTk('TCLLIBPATH', value)
-  #
-
-  """Append value to TKLIBPATH environment variable"""
-  def addToTkLibPath(self, value):
-    self.__addToReservedTclTk('TKLIBPATH', value)
+    self.addToEnviron('PYTHONPATH', value)
   #
 
   """Set environment variable to value"""
@@ -112,30 +125,24 @@ class SalomeRunner:
       del os.environ[name]
   #
 
+  """Append value to environment variable"""
+  def addToEnviron(self, name, value, separator=os.pathsep):
+    if value == '':
+      return
+
+    value = os.path.expandvars(value) # expand environment variables
+    self.getLogger().debug("Add to %s: %s", name, value)
+    env = os.getenv(name, None)
+    if env is None:
+      os.environ[name] = value
+    else:
+      os.environ[name] = value + separator + env
+  #
+
   ###################################
   # This begins the private section #
   ###################################
 
-  def _usage(self, unused=[]):
-    #exeName = os.path.splitext(os.path.basename(__file__))[0]
-
-    msg = '''\
-Usage: salome [command] [options] [--config=file1,...,filen]
-
-Commands:
-    start         Launches SALOME virtual application [DEFAULT]
-    shell         Executes a script under SALOME application environment
-    connect       Connects a Python console to the active SALOME session
-    killall       Kill all SALOME running sessions
-    info          Display some information about SALOME
-    help          Show this message
-    coffee        Yes! SALOME can also make coffee!!"\
-
-'''
-
-    print msg
-  #
-
   def __parseArguments(self, args):
     if len(args) == 0 or args[0].startswith("-"):
       return None, args
@@ -171,7 +178,7 @@ Commands:
 
     if command is None:
       if args and args[0] in ["-h","--help","help"]:
-        self._usage()
+        usage()
         sys.exit(0)
       # try to default to "start" command
       command = "_runAppli"
@@ -195,8 +202,8 @@ Commands:
       sys.exit(1)
   #
 
-  def __setEnvironmentFromConfigFile(self, filename):
-    unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved=['PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH'])
+  def __setEnvironmentFromConfigFile(self, filename, reserved=[]):
+    unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
 
     # unset variables
     for var in unsetVars:
@@ -206,7 +213,7 @@ Commands:
     for reserved in reservedDict:
       a = filter(None, reservedDict[reserved]) # remove empty elements
       reformattedVals = ':'.join(a)
-      self.__addToReserved(reserved, reformattedVals)
+      self.addToEnviron(reserved, reformattedVals)
       pass
 
     for key,val in configVars:
@@ -216,34 +223,6 @@ Commands:
     sys.path[:0] = os.getenv('PYTHONPATH','').split(':')
   #
 
-  def __addToReserved(self, name, value):
-    if value == '':
-      return
-
-    value = os.path.expandvars(value) # expand environment variables
-    self.getLogger().debug("Add to %s: %s", name, value)
-    env = os.getenv(name, None)
-    if env is None:
-      os.environ[name] = value
-    else:
-      os.environ[name] = value + os.pathsep + env
-  #
-
-  def __addToReservedTclTk(self, name, value):
-    if value == '':
-      return
-
-    value = os.path.expandvars(value) # expand environment variables
-    self.getLogger().debug("Add to %s: %s", name, value)
-    env = os.getenv(name, None)
-    #http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
-    #Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
-    if env is None:
-      os.environ[name] = value
-    else:
-      os.environ[name] = value + " " + env #explicitely whitespace
-  #
-
   def _runAppli(self, args=[]):
     # Initialize SALOME environment
     sys.argv = ['runSalome'] + args
@@ -265,7 +244,8 @@ Commands:
     scriptArgs = getScriptsAndArgs(args)
     command = formatScriptsAndArgs(scriptArgs)
     if command:
-      proc = subprocess.Popen(command, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+      command = command.split(' ')
+      proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
       return proc.communicate()
     else:
       absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
@@ -285,8 +265,29 @@ Commands:
   #
 
   def _killAll(self, args=[]):
-    from killSalome import killAllPorts
-    killAllPorts()
+    absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
+    try:
+      import PortManager # mandatory
+      from multiprocessing import Process
+      from killSalomeWithPort import killMyPort
+      ports = PortManager.getBusyPorts()
+
+      if ports:
+        import tempfile
+        for port in ports:
+          with tempfile.NamedTemporaryFile():
+            p = Process(target = killMyPort, args=(port,))
+            p.start()
+            p.join()
+
+      p = Process(target = killMyPort, args=(2809,))
+      p.start()
+      p.join()
+    except ImportError:
+      from killSalome import killAllPorts
+      killAllPorts()
+      pass
+
   #
 
   def _showInfo(self, args=[]):
@@ -294,6 +295,10 @@ Commands:
     self._runAppli(["--version"])
   #
 
+  def _usage(self, unused=[]):
+    usage()
+  #
+
   def _makeCoffee(self, args=[]):
     print "                        ("
     print "                          )     ("
@@ -352,5 +357,5 @@ if __name__ == "__main__":
     if err:
       sys.stderr.write(err)
   else:
-    SalomeRunner()._usage()
+    usage()
 #