Salome HOME
Revert "Synchronize adm files"
[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=[]):
38   usage = "Usage: %prog [options] [command]"
39   epilog  = """\n
40 If the command is not given a shell is opened; else execute the given command.
41 Command may be a series of Python scripts with arguments: [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
42 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,...
43 \n
44 If PORT and MACHINE are not given, try to connect to the last active session on the local machine.
45 If PORT and MACHINE are given, try to connect to the remote session associated with PORT on MACHINE.
46 If MACHINE is not given, try to connect to the session associated to PORT on the local machine.
47 If PORT is not given, try to connect to the remote session associated to port 2810 on MACHINE.\n\n"""
48   parser = MyParser(usage=usage, epilog=epilog)
49   parser.add_option("-p", "--port", metavar="<port>", default=0,
50                     action="store", type="string", dest="port",
51                     help="The port to connect to."
52                     )
53   parser.add_option("-m", "--machine", metavar="<machine>", default=0,
54                     action="store", type="string", dest="host",
55                     help="The machine to connect to."
56                     )
57   try:
58     (options, args) = parser.parse_args(args)
59   except Exception, e:
60     print e
61     return
62
63   port = options.port
64   host = options.host
65
66   # :GLITCH: this code defines specific environment variables (OMNIORB_CONFIG, NSPORT,
67   # NSHOST) which are later used by other modules. Working, but not really "safe"...
68   if not port:
69     if not host:
70       # neither MACHINE nor PORT are given
71       # --- set omniORB configuration to current session if any
72       omniorbUserPath = os.environ['OMNIORB_USER_PATH']
73       fileOmniConfig = omniorbUserPath + '/.omniORB_' + os.environ['USER'] + '_last.cfg'
74       if os.path.isfile(fileOmniConfig):
75         os.environ['OMNIORB_CONFIG'] = fileOmniConfig
76         # --- set environment variables for port and hostname of NamingService
77         host, port = getNSparams()
78       else:
79         # No running session
80         host = "no_host"
81         port = "no_port"
82     else:
83       # only MACHINE is given
84       port = '2810'
85       _writeConfigFile(port, host)
86     #
87   else:
88     if not host:
89       # only PORT is given
90       host = socket.gethostname()
91     # both MACHINE and PORT are given
92     _writeConfigFile(port, host)
93   #
94   os.environ['NSPORT'] = port
95   os.environ['NSHOST'] = host
96 #
97
98 # --- set the OMNIORB_CONFIG file and environment relative to this run of SALOME
99 def _writeConfigFile(port, host):
100   path = os.environ['OMNIORB_USER_PATH']
101   kwargs = {'with_username' : os.environ['USER']}
102
103   from ORBConfigFile import writeORBConfigFile
104   [ filename, msgSize ] = writeORBConfigFile(path, host, port, kwargs)
105
106   os.environ['OMNIORB_CONFIG'] = filename
107 #
108
109 # command looks like a Bash command-line:
110 # script1.py [args] ; script2.py [args] ; ...
111 def runSession(command):
112   if command:
113     sep = ";"
114     if sys.platform == "win32":
115       sep= "&"
116     command = command.split(sep)
117     outmsg = []
118     errmsg = []
119     for cmd in command:
120       save_cmd = cmd
121       cmd = cmd.strip().split(' ')
122       #proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
123       proc = subprocess.Popen(cmd)
124       (stdoutdata, stderrdata) = proc.communicate()
125       if stdoutdata:
126         outmsg.append(stdoutdata)
127       if stderrdata:
128         errmsg.append(stderrdata)
129
130       if proc.returncode != 0:
131         errmsg.append("Error raised when executing command: %s\n"%save_cmd)
132         if outmsg:
133           sys.stdout.write("".join(outmsg))
134         if errmsg:
135           sys.stderr.write("".join(errmsg))
136         sys.exit(proc.returncode)
137
138     return ("".join(outmsg), "".join(errmsg))
139   else:
140     absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
141     cmd = ["/bin/bash",  "--rcfile", absoluteAppliPath + "/.bashrc" ]
142     proc = subprocess.Popen(cmd, shell=False, close_fds=True)
143     return proc.communicate()
144 #