Salome HOME
Merge branch 'agy/ParallelContainerLaunch'
[modules/kernel.git] / bin / runSession.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23
24 import os
25 import sys
26 from optparse import OptionParser
27 from NSparam import getNSparams
28 import socket
29 import subprocess
30
31 # Use to display newlines (\n) in epilog
32 class MyParser(OptionParser):
33     def format_epilog(self, formatter):
34         return self.epilog
35 #
36
37 def configureSession(args=None):
38   if args is None:
39     args = []
40   usage = "Usage: %prog [options] [command]"
41   epilog  = """\n
42 If the command is not given a shell is opened; else execute the given command.
43 Command may be a series of Python scripts with arguments: [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
44 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,...
45 \n
46 If PORT and MACHINE are not given, try to connect to the last active session on the local machine.
47 If PORT and MACHINE are given, try to connect to the remote session associated with PORT on MACHINE.
48 If MACHINE is not given, try to connect to the session associated to PORT on the local machine.
49 If PORT is not given, try to connect to the remote session associated to port 2810 on MACHINE.\n\n"""
50   parser = MyParser(usage=usage, epilog=epilog)
51   parser.add_option("-p", "--port", metavar="<port>", default=0,
52                     action="store", type="string", dest="port",
53                     help="The port to connect to."
54                     )
55   parser.add_option("-m", "--machine", metavar="<machine>", default=0,
56                     action="store", type="string", dest="host",
57                     help="The machine to connect to."
58                     )
59   try:
60     (options, args) = parser.parse_args(args)
61   except Exception, e:
62     print e
63     return
64
65   port = options.port
66   host = options.host
67
68   # :GLITCH: this code defines specific environment variables (OMNIORB_CONFIG, NSPORT,
69   # NSHOST) which are later used by other modules. Working, but not really "safe"...
70   if not port:
71     if not host:
72       # neither MACHINE nor PORT are given
73       # --- set omniORB configuration to current session if any
74       omniorbUserPath = os.environ['OMNIORB_USER_PATH']
75       fileOmniConfig = omniorbUserPath + '/.omniORB_' + os.environ['USER'] + '_last.cfg'
76       if os.path.isfile(fileOmniConfig):
77         os.environ['OMNIORB_CONFIG'] = fileOmniConfig
78         # --- set environment variables for port and hostname of NamingService
79         host, port = getNSparams()
80       else:
81         # No running session
82         host = "no_host"
83         port = "no_port"
84     else:
85       # only MACHINE is given
86       port = '2810'
87       _writeConfigFile(port, host)
88     #
89   else:
90     if not host:
91       # only PORT is given
92       host = socket.gethostname()
93     # both MACHINE and PORT are given
94     _writeConfigFile(port, host)
95   #
96   os.environ['NSPORT'] = port
97   os.environ['NSHOST'] = host
98 #
99
100 # --- set the OMNIORB_CONFIG file and environment relative to this run of SALOME
101 def _writeConfigFile(port, host):
102   path = os.environ['OMNIORB_USER_PATH']
103   kwargs = {'with_username' : os.environ['USER']}
104
105   from ORBConfigFile import writeORBConfigFile
106   [ filename, msgSize ] = writeORBConfigFile(path, host, port, kwargs)
107
108   os.environ['OMNIORB_CONFIG'] = filename
109 #
110
111 # command looks like a Bash command-line:
112 # script1.py [args] ; script2.py [args] ; ...
113 def runSession(command):
114   if command:
115     sep = ";"
116     if sys.platform == "win32":
117       sep= "&"
118     command = command.split(sep)
119     outmsg = []
120     errmsg = []
121     for cmd in command:
122       save_cmd = cmd
123       cmd = cmd.strip().split(' ')
124       #proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
125       proc = subprocess.Popen(cmd)
126       (stdoutdata, stderrdata) = proc.communicate()
127       if stdoutdata:
128         outmsg.append(stdoutdata)
129       if stderrdata:
130         errmsg.append(stderrdata)
131
132       if proc.returncode != 0:
133         errmsg.append("Error raised when executing command: %s\n"%save_cmd)
134         if outmsg:
135           sys.stdout.write("".join(outmsg))
136         if errmsg:
137           sys.stderr.write("".join(errmsg))
138         sys.exit(proc.returncode)
139
140     return ("".join(outmsg), "".join(errmsg))
141   else:
142     absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
143     cmd = ["/bin/bash",  "--rcfile", absoluteAppliPath + "/.bashrc" ]
144     proc = subprocess.Popen(cmd, shell=False, close_fds=True)
145     return proc.communicate()
146 #