Salome HOME
updated copyright message
[modules/kernel.git] / bin / setenv.py
1 #!/usr/bin/env python3
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
4 #
5 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24
25 import sys, os, string, glob, time, pickle
26 from launchConfigureParser import verbose
27
28 # this file is extraction of set_env from runSalome.py
29 # for reusage in automated tests
30
31 # salome_subdir variable is used for composing paths like $KERNEL_ROOT_DIR/share/salome/resources, etc.
32 # before moving to SUIT-based gui, instead of salome_subdir there was args['appname'] used.
33 # but after - 'appname'  = "SalomeApp", so using it in making the subdirectory is an error.
34 salome_subdir = "salome"
35
36
37 # -----------------------------------------------------------------------------
38
39 def add_path(directory, variable_name):
40     """Function helper to add environment variables"""
41     if variable_name not in os.environ:
42         os.environ[variable_name] = ""
43         pass
44     if os.path.exists(directory):
45         newpath=[]
46         for _dir in os.environ[variable_name].split(os.pathsep):
47             if os.path.exists(_dir):
48                 if not os.path.samefile(_dir, directory):
49                     newpath.append(_dir)
50             else:
51                 if os.path.abspath(_dir) != os.path.abspath(directory):
52                   newpath.append(_dir)
53             pass
54         newpath[:0] = [ directory ]
55         newpath = os.pathsep.join(newpath)
56         os.environ[variable_name] = newpath
57         if variable_name == "PYTHONPATH":
58             sys.path[:0] = [os.path.realpath(directory)]
59
60 # -----------------------------------------------------------------------------
61
62 __lib__dir__ = None
63 def get_lib_dir():
64     global __lib__dir__
65     if __lib__dir__: return __lib__dir__
66     import platform
67     __lib__dir__ = "lib"
68     return __lib__dir__
69
70 # -----------------------------------------------------------------------------
71
72 def get_config(silent=False, exeName=None, keepEnvironment=True):
73     """
74     Get list of modules, paths.
75
76     Read args from launch configure xml file and command line options.
77     Check variables <module>_ROOT_DIR and set list of used modules.
78     Return args, modules_list, modules_root_dir
79     """
80
81     # read args from launch configure xml file and command line options
82
83
84     import launchConfigureParser
85     args = launchConfigureParser.get_env(exeName=exeName, keepEnvironment=keepEnvironment)
86
87
88     # Check variables <module>_ROOT_DIR
89     # and set list of used modules (without KERNEL)
90
91     modules_list = []
92     if "modules" in args:
93         modules_list += [a for a in args["modules"] if a.strip()]
94     # KERNEL must be last in the list to locate it at the first place in PATH
95     if args["gui"] :
96         modules_list[:0] = ["GUI"]
97     modules_list[:0] = ["KERNEL"]
98     modules_list.reverse()
99
100     modules_root_dir = {}
101
102     to_remove_list=[]
103     for module in modules_list :
104         module_variable=module+"_ROOT_DIR"
105         if module_variable not in os.environ:
106             if not silent:
107                 print("*******************************************************")
108                 print("*")
109                 print("* Environment variable",module_variable,"must be set")
110                 print("* Module", module, "will be not available")
111                 print("*")
112                 print("********************************************************")
113                 pass
114             to_remove_list.append(module)
115             continue
116             pass
117         module_root_dir = os.environ[module_variable]
118         modules_root_dir[module]=module_root_dir
119
120     for to_remove in to_remove_list:
121         modules_list.remove(to_remove)
122
123     while "KERNEL" in modules_list:
124         modules_list.remove("KERNEL")
125         pass
126
127     while "GUI" in modules_list:
128         modules_list.remove("GUI")
129         pass
130
131     return args, modules_list, modules_root_dir
132
133 # -----------------------------------------------------------------------------
134
135 def set_env(args, modules_list, modules_root_dir, silent=False, keepEnvironment=True):
136     """Add to the PATH-variables modules specific paths"""
137
138     import os
139     from salome_utils import getLogDir, generateFileName, makeTmpDir, getPortNumber
140
141     if 'launcher' in args:
142       pos = args['launcher'].find(":")
143       if pos != -1:
144         machine = args['launcher'][0:pos]
145         port = args['launcher'][pos+1:]
146         os.environ["NSPORT"] = port
147
148     # create temporary directory for environment files needed by modules from the list
149     port = getPortNumber(False)
150     if port:
151         tmp_dir = getLogDir()
152         env_dir = generateFileName(tmp_dir, prefix="env", with_port=True)
153         makeTmpDir(env_dir)
154         pass
155
156     python_version="python%d.%d" % sys.version_info[0:2]
157     modules_root_dir_list = []
158     if os.getenv('SALOME_BATCH') == None:
159       os.putenv('SALOME_BATCH','0')
160     if args["gui"] :
161         modules_list = modules_list[:] + ["GUI"]
162     if not keepEnvironment:
163         modules_list = modules_list[:] + ["KERNEL"]
164         for module in modules_list :
165             if module in modules_root_dir:
166                 module_root_dir = modules_root_dir[module]
167                 if module_root_dir not in modules_root_dir_list:
168                   modules_root_dir_list[:0] = [module_root_dir]
169                 if sys.platform == "win32":
170                   add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
171                          "PATH")
172                 elif sys.platform == "darwin":
173                   add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
174                          "DYLD_LIBRARY_PATH")
175                 else:
176                   add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
177                          "LD_LIBRARY_PATH")
178                 add_path(os.path.join(module_root_dir,"bin",salome_subdir),
179                          "PATH")
180                 if os.path.exists(os.path.join(module_root_dir, "examples")):
181                     add_path(os.path.join(module_root_dir,"examples"),
182                              "PYTHONPATH")
183                     pass
184                 add_path(os.path.join(module_root_dir,"bin",salome_subdir),
185                          "PYTHONPATH")
186                 # add lib before site-packages to load script instead of dll if any (win32 platform)
187                 add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
188                          "PYTHONPATH")
189                 add_path(os.path.join(module_root_dir,get_lib_dir(),
190                                       python_version,"site-packages",
191                                       salome_subdir),
192                          "PYTHONPATH")
193                 import platform
194                 if platform.machine() == "x86_64":
195                     add_path(os.path.join(module_root_dir,"lib64",
196                                           python_version,"site-packages",
197                                           salome_subdir),
198                              "PYTHONPATH")
199                     pass
200                 add_path(os.path.join(module_root_dir,get_lib_dir(),
201                                       python_version,"site-packages",
202                                       salome_subdir,
203                                       "shared_modules"),
204                          "PYTHONPATH")
205
206                 # set environment by modules from the list
207                 if port:
208                     try:
209                         import importlib
210                         mod=importlib.import_module(module.lower()+"_setenv")
211                         mod.set_env(args)
212                         pass
213                     except Exception:
214                         pass
215                     pass
216                 pass
217             pass
218
219         if sys.platform == 'win32':
220             os.environ["SALOMEPATH"]=";".join(modules_root_dir_list)
221         else:
222             os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
223
224         pass
225     # set trace environment variable
226
227     if "SALOME_trace" not in os.environ:
228         os.environ["SALOME_trace"]="local"
229     if args['file']:
230         os.environ["SALOME_trace"]="file:"+args['file'][0]
231     if args['logger']:
232         os.environ["SALOME_trace"]="with_logger"
233
234 # -----------------------------------------------------------------------------
235
236 def main(silent=False, exeName=None):
237     keep_env = not os.getenv('SALOME_PLEASE_SETUP_ENVIRONMENT_AS_BEFORE')
238     args, modules_list, modules_root_dir = get_config(silent=silent, exeName=exeName, keepEnvironment=keep_env)
239     set_env(args, modules_list, modules_root_dir, silent=silent, keepEnvironment=keep_env)
240     return args
241
242 # -----------------------------------------------------------------------------
243
244 if __name__ == "__main__":
245    import user
246    args = main()