Salome HOME
Use "default" theme for Sphinx < 1.3
[modules/kernel.git] / bin / runSession.py
index 5d5f71886c61d3dd55379035fca5cd55827a048a..8dac79131a2c40eba8c9d5ca6da2a6e8148f444e 100644 (file)
@@ -1,5 +1,5 @@
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2015  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
@@ -28,7 +28,8 @@ from NSparam import getNSparams
 import socket
 import subprocess
 import re
-from salomeContextUtils import getScriptsAndArgs, formatScriptsAndArgs
+from salomeContextUtils import getScriptsAndArgs, formatScriptsAndArgs, getShortAndExtraArgs
+from salome_utils import getUserName
 
 # Use to display newlines (\n) in epilog
 class MyParser(OptionParser):
@@ -43,25 +44,63 @@ class SessionParameters:
     self.machine = machine
     self.user = user
     self.directory = directory
+  #
+  def __repr__(self):
+    msg = "\n# Session Parameters:\n"
+    msg += "     * mode: %s\n"%self.mode
+    msg += "     * port: %s\n"%self.port
+    msg += "     * machine: %s\n"%self.machine
+    msg += "     * user: %s\n"%self.user
+    msg += "     * directory: %s\n"%self.directory
+    return msg
+  #
 #
 
-def configureSession(args=None):
+def configureSession(args=None, exe=None):
   if args is None:
     args = []
-  usage = "Usage: %prog [options] [command]"
+  if exe:
+      usage = "Usage: %s [options] [command] [-- <extra>]"%exe
+  else:
+      usage = "Usage: %prog [options] [command] [-- <extra>]"
   epilog  = """\n
-If the command is not given a shell is opened; else execute the given command.
-Command may be a series of Python scripts with arguments: [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
-Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,...
-\n
-If PORT and MACHINE are not given, try to connect to the last active session on the local machine.
-If PORT and MACHINE are given, try to connect to the remote session associated with PORT on MACHINE.
-If MACHINE is not given, try to connect to the session associated to PORT on the local machine.
-If PORT is not given, try to connect to the remote session associated to port 2810 on MACHINE.
+If command is not given a shell is opened; else execute the given command.\n
+* Command may be an executable script or program, either identified by its
+  full path or located in a directory pointed by a system variable (e.g.
+  PATH).\n
+* Command may also be a series of Python scripts with arguments:
+  [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
+Python file arguments, if any, must be comma-separated (without blank
+  characters) and prefixed by "args:" keyword (without quotes).
+For example:
+       salome shell hello.py add.py args:1,2 hello.py args:you
+will successively say hello, add 1+2, and say hello to you.\n
+The double dash (--) syntax indicates an extra command to be run "as is". It
+  allows calling a extern program or system command with options and
+  arguments, using the syntax: -- <program> [options] [arguments].
+For example:
+       salome shell -- ls -l *.py
+       salome shell -- python -tt hello.py
 \n
+If PORT and MACHINE are not given, try to connect to the last active session
+  on the local machine.
+If PORT and MACHINE are given, try to connect to the remote session associated
+  with PORT on MACHINE.
+If MACHINE is not given, try to connect to the session associated to PORT on
+  the local machine.
+If PORT is not given, try to connect to the remote session associated to port
+  2810 on MACHINE.\n
 If MACHINE is remote, the following options MUST be provided:
      * DIRECTORY: The full path to the salome command on remote machine.
-     * USER: The user on the computer to connect to.
+     * USER: The user on the computer to connect to.\n
+In case of remote call, syntax "out:res1,res2,..." can be used to get results
+  from remote machine.
+For example:
+       salome shell -m remotemachine -p 2810 -u myself -d /full/path/to/salome
+  concatenate.py args:file1.txt,file2.txt out:result.txt
+User "myself" connects to remotemachine to run the script concatenate.py in
+  a SALOME session on port 2810; the script takes two input parameters and
+  produces one result file.\n
 """
   parser = MyParser(usage=usage, epilog=epilog)
   parser.add_option("-p", "--port", metavar="<port>", default=0,
@@ -78,8 +117,10 @@ If MACHINE is remote, the following options MUST be provided:
   parser.add_option('-u', '--user', dest="user", default=None,
                     help="[Remote mode] The user on the computer to connect to."
                     )
+
+  short_args, extra_args = getShortAndExtraArgs(args)
   try:
-    (options, args) = parser.parse_args(args)
+    (options, args) = parser.parse_args(short_args)
   except Exception, e:
     print e
     return
@@ -94,7 +135,7 @@ If MACHINE is remote, the following options MUST be provided:
       # neither MACHINE nor PORT are given
       # --- set omniORB configuration to current session if any
       omniorbUserPath = os.environ['OMNIORB_USER_PATH']
-      fileOmniConfig = omniorbUserPath + '/.omniORB_' + os.environ['USER'] + '_last.cfg'
+      fileOmniConfig = omniorbUserPath + '/.omniORB_' + getUserName() + '_last.cfg'
       if os.path.isfile(fileOmniConfig):
         os.environ['OMNIORB_CONFIG'] = fileOmniConfig
         # --- set environment variables for port and hostname of NamingService
@@ -119,20 +160,19 @@ If MACHINE is remote, the following options MUST be provided:
   os.environ['NSHOST'] = host
 
   # determine running mode, taht is either 'local' or 'remote'
-  from salomeContextUtils import getHostname
-  here = getHostname()
+  here = socket.gethostname()
   mode = "local"
   if host != here and host != "localhost" and host != "no_host":
     mode="remote"
     pass
   params = SessionParameters(mode, port, host, options.user, options.directory)
-  return params, args
+  return params, args+extra_args
 #
 
 # --- set the OMNIORB_CONFIG file and environment relative to this run of SALOME
 def _writeConfigFile(port, host):
   path = os.environ['OMNIORB_USER_PATH']
-  kwargs = {'with_username' : os.environ['USER']}
+  kwargs = {'with_username' : getUserName()}
 
   from ORBConfigFile import writeORBConfigFile
   [ filename, msgSize ] = writeORBConfigFile(path, host, port, kwargs)
@@ -152,25 +192,36 @@ def __runLocalSession(command):
     errmsg = []
     for cmd in command:
       single_cmd = cmd.strip().split(' ')
-      proc = subprocess.Popen(single_cmd)
-      (stdoutdata, stderrdata) = proc.communicate() # Wait for process to terminate
-      if stdoutdata:
-        outmsg.append(stdoutdata)
-      if stderrdata:
-        errmsg.append(stderrdata)
-
-      if proc.returncode != 0:
+      any_error = False
+      try:
+        proc = subprocess.Popen(single_cmd)
+        (stdoutdata, stderrdata) = proc.communicate() # Wait for process to terminate
+        if stdoutdata:
+          outmsg.append(stdoutdata)
+        if stderrdata:
+          errmsg.append(stderrdata)
+
+        if proc.returncode != 0:
+          any_error = True
+      except:
+          any_error = True
+          pass
+
+      if any_error:
         errmsg.append("Error raised when executing command: %s\n"%cmd)
         if outmsg:
           sys.stdout.write("".join(outmsg))
         if errmsg:
           sys.stderr.write("".join(errmsg))
-        sys.exit(proc.returncode)
+        sys.exit(1)
 
     return ("".join(outmsg), "".join(errmsg))
   else:
     absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
-    cmd = ["/bin/bash",  "--rcfile", absoluteAppliPath + "/.bashrc" ]
+    if sys.platform == "win32":
+      cmd = ["cmd", "/K", "set PROMPT=[SALOME] $P$G"]
+    else:
+      cmd = ["/bin/bash",  "--rcfile", absoluteAppliPath + "/.bashrc" ]
     proc = subprocess.Popen(cmd, shell=False, close_fds=True)
     return proc.communicate()
 #
@@ -244,10 +295,10 @@ def __runRemoteSession(sa_obj, params):
   tmp_in, tmp_out, tmp_script = __copyFiles(params.user, params.machine, script, sa_obj.args or [], sa_obj.out or [])
 
   # execute command on the remote SALOME application
-  command = "ssh %s@%s %s/runSession " % (params.user, params.machine, params.directory)
+  command = "ssh %s@%s %s/salome shell " % (params.user, params.machine, params.directory)
   if params.port:
     command = command + "-p %s "%params.port
-  command = command + " ".join([header,tmp_script] + tmp_in)
+  command = command + " %s %s args:%s"%(header, tmp_script, ",".join(tmp_in))
   print '[  SSH   ] ' + command
   os.system(command)
 
@@ -271,7 +322,6 @@ def __runRemoteSession(sa_obj, params):
 
 def runSession(params, args):
   scriptArgs = getScriptsAndArgs(args)
-  command = formatScriptsAndArgs(scriptArgs)
 
   if params.mode == "local":
     command = formatScriptsAndArgs(scriptArgs)