Salome HOME
Porting to Python 2.6 - add coding page specification for Python scripts
[modules/kernel.git] / bin / setenv.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, 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.
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 import sys, os, string, glob, time, pickle
25 import orbmodule
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 sys.platform == "win32":
42       splitsym = ";"
43     else:
44       splitsym = ":"
45     if not os.environ.has_key(variable_name):
46         os.environ[variable_name] = ""
47         pass
48     if os.path.exists(directory):
49         newpath=[]
50         for _dir in os.environ[variable_name].split(splitsym):
51             if os.path.exists(_dir):
52                 if sys.platform != "win32":
53                     if not os.path.samefile(_dir, directory):
54                         newpath.append(_dir)
55                 else:
56                     newpath.append(_dir)
57             else:
58                 if os.path.abspath(_dir) != os.path.abspath(directory):
59                   newpath.append(_dir)
60             pass
61         import string
62         newpath[:0] = [ directory ]
63         newpath = string.join(newpath, splitsym)
64         os.environ[variable_name] = newpath
65         if variable_name == "PYTHONPATH":
66             sys.path[:0] = [directory]
67
68 # -----------------------------------------------------------------------------
69
70 __lib__dir__ = None
71 def get_lib_dir():
72     global __lib__dir__
73     if __lib__dir__: return __lib__dir__
74     import platform
75     __lib__dir__ = "lib"
76     return __lib__dir__
77
78 # -----------------------------------------------------------------------------
79
80 def get_config(silent=False):
81     """
82     Get list of modules, paths.
83     
84     Read args from launch configure xml file and command line options.
85     Check variables <module>_ROOT_DIR and set list of used modules.
86     Return args, modules_list, modules_root_dir    
87     """
88     
89     # read args from launch configure xml file and command line options
90
91     #*** Test additional option
92     #*** import optparse
93     #*** help_str = "Test options addition."
94     #*** o_j = optparse.Option("-j", "--join", action="store_true", dest="join", help=help_str)
95
96     import launchConfigureParser
97     args = launchConfigureParser.get_env()
98
99     #*** Test additional option
100     #*** args = launchConfigureParser.get_env([o_j])
101     #*** if args.has_key("join"): print args["join"]
102
103     # Check variables <module>_ROOT_DIR
104     # and set list of used modules (without KERNEL)
105
106     modules_list = []
107     if args.has_key("modules"):
108         modules_list += args["modules"]
109     # KERNEL must be last in the list to locate it at the first place in PATH
110     if args["gui"] :
111         modules_list[:0] = ["GUI"]
112     modules_list[:0] = ["KERNEL"]
113     modules_list.reverse()
114
115     modules_root_dir = {}
116
117     to_remove_list=[]
118     for module in modules_list :
119         module_variable=module+"_ROOT_DIR"
120         if not os.environ.has_key(module_variable):
121             if not silent:
122                 print "*******************************************************"
123                 print "*"
124                 print "* Environment variable",module_variable,"must be set"
125                 print "* Module", module, "will be not available"
126                 print "*"
127                 print "********************************************************"
128                 pass
129             to_remove_list.append(module)
130             continue
131             pass
132         module_root_dir = os.environ[module_variable]
133         modules_root_dir[module]=module_root_dir
134
135     for to_remove in to_remove_list:
136         modules_list.remove(to_remove)
137
138     while "KERNEL" in modules_list:
139         modules_list.remove("KERNEL")
140         pass
141
142     while "GUI" in modules_list:
143         modules_list.remove("GUI")
144         pass
145
146     return args, modules_list, modules_root_dir
147
148 # -----------------------------------------------------------------------------
149
150 def set_env(args, modules_list, modules_root_dir, silent=False):
151     """Add to the PATH-variables modules specific paths"""
152     
153     import os
154     from salome_utils import getTmpDir, generateFileName, makeTmpDir, getPortNumber
155
156     # create temporary directory for environment files needed by modules from the list
157     port = getPortNumber(False)
158     if port:
159         tmp_dir = getTmpDir()
160         env_dir = generateFileName(tmp_dir, prefix="env", with_port=True)
161         makeTmpDir(env_dir)
162         pass
163
164     python_version="python%d.%d" % sys.version_info[0:2]
165     modules_root_dir_list = []
166     if os.getenv('SALOME_BATCH') == None:
167       os.putenv('SALOME_BATCH','0')
168     if args["gui"] :
169         modules_list = modules_list[:] + ["GUI"] 
170     modules_list = modules_list[:] + ["KERNEL"] 
171     for module in modules_list :
172         if modules_root_dir.has_key(module):
173             module_root_dir = modules_root_dir[module]
174             modules_root_dir_list[:0] = [module_root_dir]
175             if sys.platform == "win32":
176               add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
177                      "PATH")
178             else:
179               add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
180                      "LD_LIBRARY_PATH")
181             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
182                      "PATH")
183             if os.path.exists(module_root_dir + "/examples") :
184                 add_path(os.path.join(module_root_dir,"examples"),
185                          "PYTHONPATH")
186                 pass
187             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
188                      "PYTHONPATH")
189             # add lib before site-packages to load script instead of dll if any (win32 platform)
190             add_path(os.path.join(module_root_dir,get_lib_dir(),salome_subdir),
191                      "PYTHONPATH")
192             add_path(os.path.join(module_root_dir,get_lib_dir(),
193                                   python_version,"site-packages",
194                                   salome_subdir),
195                      "PYTHONPATH")
196             add_path(os.path.join(module_root_dir,get_lib_dir(),
197                                   python_version,"site-packages",
198                                   salome_subdir,
199                                   "shared_modules"),
200                      "PYTHONPATH")
201                      
202             # set environment by modules from the list
203             if port:
204                 try:
205                     mod=__import__(module.lower()+"_setenv")
206                     mod.set_env(args)
207                     pass
208                 except:
209                     pass
210                 pass
211             pass
212         pass
213
214     if sys.platform == 'win32':
215         os.environ["SALOMEPATH"]=";".join(modules_root_dir_list)
216     else:
217         os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
218     
219     # set trace environment variable
220     
221     if not os.environ.has_key("SALOME_trace"):
222         os.environ["SALOME_trace"]="local"
223     if args['file']:
224         os.environ["SALOME_trace"]="file:"+args['file'][0]
225     if args['logger']:
226         os.environ["SALOME_trace"]="with_logger"
227
228     # set resources variables if not yet set
229
230     os.environ["CSF_SALOMEDS_ResourcesDefaults"] \
231     = os.path.join(modules_root_dir["KERNEL"],"share",
232                    salome_subdir,"resources","kernel")
233
234 # -----------------------------------------------------------------------------
235
236 def main(silent=False):
237     args, modules_list, modules_root_dir = get_config(silent=silent)
238     set_env(args, modules_list, modules_root_dir, silent=silent)
239     return args
240
241 # -----------------------------------------------------------------------------
242
243 if __name__ == "__main__":
244    import user
245    args = main()