Salome HOME
Handle environment file for binary packages
[tools/sat.git] / src / environment.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import subprocess
21 import string
22 import sys
23
24 import src
25
26 class Environ:
27     '''Class to manage the environment context
28     '''
29     def __init__(self, environ=None):
30         '''Initialization. If the environ argument is passed, the environment
31            will be add to it, else it is the external environment.
32            
33         :param environ dict:  
34         '''
35         if environ is not None:
36             self.environ = environ
37         else:
38             self.environ = os.environ
39
40     def __repr__(self):
41         """easy non exhaustive quick resume for debug print
42         """
43         res={}
44         res["environ"]=self.environ
45         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
46
47     def _expandvars(self, value):
48         '''replace some $VARIABLE into its actual value in the environment
49         
50         :param value str: the string to be replaced
51         :return: the replaced variable
52         :rtype: str
53         '''
54         if "$" in value:
55             # The string.Template class is a string class 
56             # for supporting $-substitutions
57             zt = string.Template(value)
58             try:
59                 value = zt.substitute(self.environ)
60             except KeyError as exc:
61                 raise src.SatException(_("Missing definition "
62                                          "in environment: %s") % str(exc))
63         return value
64
65     def append_value(self, key, value, sep=os.pathsep):
66         '''append value to key using sep
67         
68         :param key str: the environment variable to append
69         :param value str: the value to append to key
70         :param sep str: the separator string
71         '''
72         # check if the key is already in the environment
73         if key in self.environ:
74             value_list = self.environ[key].split(sep)
75             # Check if the value is already in the key value or not
76             if not value in value_list:
77                 value_list.append(value)
78             else:
79                 value_list.append(value_list.pop(value_list.index(value)))
80             self.set(key, sep.join(value_list))
81         else:
82             self.set(key, value)
83
84     def append(self, key, value, sep=os.pathsep):
85         '''Same as append_value but the value argument can be a list
86         
87         :param key str: the environment variable to append
88         :param value str or list: the value(s) to append to key
89         :param sep str: the separator string
90         '''
91         if isinstance(value, list):
92             for v in value:
93                 self.append_value(key, v, sep)
94         else:
95             self.append_value(key, value, sep)
96
97     def prepend_value(self, key, value, sep=os.pathsep):
98         '''prepend value to key using sep
99         
100         :param key str: the environment variable to prepend
101         :param value str: the value to prepend to key
102         :param sep str: the separator string
103         '''
104         if key in self.environ:
105             value_list = self.environ[key].split(sep)
106             if not value in value_list:
107                 value_list.insert(0, value)
108             else:
109                 value_list.insert(0, value_list.pop(value_list.index(value)))
110             self.set(key, sep.join(value_list))
111         else:
112             self.set(key, value)
113
114     def prepend(self, key, value, sep=os.pathsep):
115         '''Same as prepend_value but the value argument can be a list
116         
117         :param key str: the environment variable to prepend
118         :param value str or list: the value(s) to prepend to key
119         :param sep str: the separator string
120         '''
121         if isinstance(value, list):
122             for v in value:
123                 self.prepend_value(key, v, sep)
124         else:
125             self.prepend_value(key, value, sep)
126
127     def is_defined(self, key):
128         '''Check if the key exists in the environment
129         
130         :param key str: the environment variable to check
131         '''
132         return key in self.environ.keys()
133
134     def set(self, key, value):
135         '''Set the environment variable "key" to value "value"
136         
137         :param key str: the environment variable to set
138         :param value str: the value
139         '''
140         self.environ[key] = self._expandvars(value)
141
142     def get(self, key):
143         '''Get the value of the environment variable "key"
144         
145         :param key str: the environment variable
146         '''
147         if key in self.environ:
148             return self.environ[key]
149         else:
150             return ""
151
152     def command_value(self, key, command):
153         '''Get the value given by the system command "command" 
154            and put it in the environment variable key
155         
156         :param key str: the environment variable
157         :param command str: the command to execute
158         '''
159         value = subprocess.Popen(command,
160                                  shell=True,
161                                  stdout=subprocess.PIPE,
162                                  env=self.environ).communicate()[0]
163         self.environ[key] = value
164
165
166 class SalomeEnviron:
167     """Class to manage the environment of SALOME.
168     """
169
170     def __init__(self, cfg, environ, forBuild=False, for_package=None):
171         '''Initialization.
172
173         :param cfg Config: the global config
174         :param environ Environ: the Environ instance where 
175                                 to store the environment variables
176         :param forBuild bool: If true, it is a launch environment, 
177                               else a build one
178         :param for_package str: If not None, produce a relative environment 
179                                 designed for a package. 
180         '''
181         self.environ = environ
182         self.cfg = cfg
183         self.forBuild = forBuild
184         self.for_package = for_package
185         self.silent = False
186
187     def __repr__(self):
188         """easy non exhaustive quick resume for debug print"""
189         res={}
190         res["environ"]=str(self.environ)
191         res["forBuild"]=self.forBuild
192         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
193
194     def append(self, key, value, sep=os.pathsep):
195         '''append value to key using sep
196         
197         :param key str: the environment variable to append
198         :param value str: the value to append to key
199         :param sep str: the separator string
200         '''
201         return self.environ.append(key, value, sep)
202
203     def prepend(self, key, value, sep=os.pathsep):
204         '''prepend value to key using sep
205         
206         :param key str: the environment variable to prepend
207         :param value str: the value to prepend to key
208         :param sep str: the separator string
209         '''
210         return self.environ.prepend(key, value, sep)
211
212     def is_defined(self, key):
213         '''Check if the key exists in the environment
214         
215         :param key str: the environment variable to check
216         '''
217         return self.environ.is_defined(key)
218
219     def get(self, key):
220         '''Get the value of the environment variable "key"
221         
222         :param key str: the environment variable
223         '''
224         return self.environ.get(key)
225
226     def set(self, key, value):
227         '''Set the environment variable "key" to value "value"
228         
229         :param key str: the environment variable to set
230         :param value str: the value
231         '''
232         # check if value needs to be evaluated
233         if value is not None and value.startswith("`") and value.endswith("`"):
234             res = subprocess.Popen("echo %s" % value,
235                                    shell=True,
236                                    stdout=subprocess.PIPE).communicate()
237             value = res[0].strip()
238
239         return self.environ.set(key, value)
240
241     def dump(self, out):
242         """Write the environment to out
243         
244         :param out file: the stream where to write the environment
245         """
246         for k in self.environ.environ.keys():
247             try:
248                 value = self.get(k)
249             except:
250                 value = "?"
251             out.write("%s=%s\n" % (k, value))
252
253     def add_line(self, nb_line):
254         """Add empty lines to the out stream (in case of file generation)
255         
256         :param nb_line int: the number of empty lines to add
257         """
258         if 'add_line' in dir(self.environ):
259             self.environ.add_line(nb_line)
260
261     def add_comment(self, comment):
262         """Add a commentary to the out stream (in case of file generation)
263         
264         :param comment str: the commentary to add
265         """
266         if 'add_comment' in dir(self.environ):
267             self.environ.add_comment(comment)
268
269     def add_warning(self, warning):
270         """Add a warning to the out stream (in case of file generation)
271         
272         :param warning str: the warning to add
273         """
274         if 'add_warning' in dir(self.environ):
275             self.environ.add_warning(warning)
276
277     def finish(self, required):
278         """Add a final instruction in the out file (in case of file generation)
279         
280         :param required bool: Do nothing if required is False
281         """
282         if 'finish' in dir(self.environ):
283             self.environ.add_line(1)
284             self.environ.add_comment("clean all the path")
285             self.environ.finish(required)
286
287     def set_python_libdirs(self):
288         """Set some generic variables for python library paths
289         """
290         ver = self.get('PYTHON_VERSION')
291         self.set('PYTHON_LIBDIR0', os.path.join('lib',
292                                                 'python' + ver,
293                                                 'site-packages'))
294         self.set('PYTHON_LIBDIR1', os.path.join('lib64',
295                                                 'python' + ver,
296                                                 'site-packages'))
297           
298         self.python_lib0 = self.get('PYTHON_LIBDIR0')
299         self.python_lib1 = self.get('PYTHON_LIBDIR1')
300
301     def get_names(self, lProducts):
302         """Get the products name to add in SALOME_MODULES environment variable
303            It is the name of the product, except in the case where the is a 
304            component name. And it has to be in SALOME_MODULES variable only 
305            if the product has the property has_salome_hui = "yes"
306         
307         :param lProducts list: List of products to potentially add
308         """
309         lProdHasGui = [p for p in lProducts if 'properties' in 
310             src.product.get_product_config(self.cfg, p) and
311             'has_salome_gui' in 
312             src.product.get_product_config(self.cfg, p).properties and
313             src.product.get_product_config(self.cfg,
314                                            p).properties.has_salome_gui=='yes']
315         lProdName = []
316         for ProdName in lProdHasGui:
317             pi = src.product.get_product_config(self.cfg, ProdName)
318             if 'component_name' in pi:
319                 lProdName.append(pi.component_name)
320             else:
321                 lProdName.append(ProdName)
322         return lProdName
323
324     def set_application_env(self, logger):
325         """Sets the environment defined in the APPLICATION file.
326         
327         :param logger Logger: The logger instance to display messages
328         """
329         
330         # Set the variables defined in the "environ" section
331         if 'environ' in self.cfg.APPLICATION:
332             self.add_comment("APPLICATION environment")
333             for p in self.cfg.APPLICATION.environ:
334                 val = self.cfg.APPLICATION.environ[p]
335                 # "_" means that the value must be prepended
336                 if p.startswith("_"):
337                     # separator exception for PV_PLUGIN_PATH
338                     if p[1:] == 'PV_PLUGIN_PATH':
339                         self.prepend(p[1:], val, ';')
340                     else:
341                         self.prepend(p[1:], val)
342                 elif p.endswith("_"):
343                     # separator exception for PV_PLUGIN_PATH
344                     if p[:-1] == 'PV_PLUGIN_PATH':
345                         self.append(p[:-1], val, ';')
346                     else:
347                         self.append(p[:-1], val)
348                 else:
349                     self.set(p, val)
350             self.add_line(1)
351
352         # If there is an "environ_script" section, load the scripts
353         if 'environ_script' in self.cfg.APPLICATION:
354             for pscript in self.cfg.APPLICATION.environ_script:
355                 self.add_comment("script %s" % pscript)
356                 sname = pscript.replace(" ", "_")
357                 self.run_env_script("APPLICATION_%s" % sname,
358                                 self.cfg.APPLICATION.environ_script[pscript],
359                                 logger)
360                 self.add_line(1)
361         
362         # If there is profile (SALOME), then define additional variables
363         if ('profile' in self.cfg.APPLICATION and 
364                                     "product" in self.cfg.APPLICATION.profile):
365             profile_product = self.cfg.APPLICATION.profile.product
366             product_info_profile = src.product.get_product_config(self.cfg,
367                                                             profile_product)
368             profile_share_salome = os.path.join(product_info_profile.install_dir,
369                                                 "share",
370                                                 "salome" )
371             self.set( "SUITRoot", profile_share_salome )
372             self.set( "SalomeAppConfig",
373                       os.path.join(profile_share_salome,
374                                    "resources",
375                                    profile_product.lower() ) )
376         
377
378     def set_salome_minimal_product_env(self, product_info, logger):
379         """Sets the minimal environment for a SALOME product.
380            xxx_ROOT_DIR and xxx_SRC_DIR
381         
382         :param product_info Config: The product description
383         :param logger Logger: The logger instance to display messages        
384         """
385         # set root dir
386         root_dir = product_info.name + "_ROOT_DIR"
387         if not self.is_defined(root_dir):
388             if 'install_dir' in product_info and product_info.install_dir:
389                 self.set(root_dir, product_info.install_dir)
390             elif not self.silent:
391                 logger.write("  " + _("No install_dir for product %s\n") %
392                               product_info.name, 5)
393         
394         if not self.for_package:
395             # set source dir, unless no source dir
396             if not src.product.product_is_fixed(product_info):
397                 src_dir = product_info.name + "_SRC_DIR"
398                 if not self.is_defined(src_dir):
399                     self.set(src_dir, product_info.source_dir)
400
401     def set_salome_generic_product_env(self, pi):
402         """Sets the generic environment for a SALOME product.
403         
404         :param pi Config: The product description
405         """
406         # Construct XXX_ROOT_DIR
407         env_root_dir = self.get(pi.name + "_ROOT_DIR")
408         l_binpath_libpath = []
409
410         # create additional ROOT_DIR for CPP components
411         if 'component_name' in pi:
412             compo_name = pi.component_name
413             if compo_name + "CPP" == pi.name:
414                 compo_root_dir = compo_name + "_ROOT_DIR"
415                 envcompo_root_dir = os.path.join(
416                             self.cfg.TOOLS.common.install_root, compo_name )
417                 self.set(compo_root_dir ,  envcompo_root_dir)
418                 bin_path = os.path.join(envcompo_root_dir, 'bin', 'salome')
419                 lib_path = os.path.join(envcompo_root_dir, 'lib', 'salome')
420                 l_binpath_libpath.append( (bin_path, lib_path) )
421
422         appliname = 'salome'
423         if (src.get_cfg_param(pi, 'product_type', 'SALOME').upper() 
424                             not in [ "SALOME", "SMESH_PLUGIN", "SAMPLE" ]):
425             appliname = ''
426
427         # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and 
428         # PYTHONPATH
429         bin_path = os.path.join(env_root_dir, 'bin', appliname)
430         lib_path = os.path.join(env_root_dir, 'lib', appliname)
431         l_binpath_libpath.append( (bin_path, lib_path) )
432
433         for bin_path, lib_path in l_binpath_libpath:
434             if not self.forBuild:
435                 self.prepend('PATH', bin_path)
436                 if src.architecture.is_windows():
437                     self.prepend('PATH', lib_path)
438                 else :
439                     self.prepend('LD_LIBRARY_PATH', lib_path)
440
441             l = [ bin_path, lib_path,
442                   os.path.join(env_root_dir, self.python_lib0, appliname),
443                   os.path.join(env_root_dir, self.python_lib1, appliname)
444                 ]
445             self.prepend('PYTHONPATH', l)
446
447     def set_cpp_env(self, product_info):
448         """Sets the generic environment for a SALOME cpp product.
449         
450         :param product_info Config: The product description
451         """
452         # Construct XXX_ROOT_DIR
453         env_root_dir = self.get(product_info.name + "_ROOT_DIR")
454         l_binpath_libpath = []
455
456         # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and 
457         # PYTHONPATH
458         bin_path = os.path.join(env_root_dir, 'bin')
459         lib_path = os.path.join(env_root_dir, 'lib')
460         l_binpath_libpath.append( (bin_path, lib_path) )
461
462         for bin_path, lib_path in l_binpath_libpath:
463             if not self.forBuild:
464                 self.prepend('PATH', bin_path)
465                 if src.architecture.is_windows():
466                     self.prepend('PATH', lib_path)
467                 else :
468                     self.prepend('LD_LIBRARY_PATH', lib_path)
469
470             l = [ bin_path, lib_path,
471                   os.path.join(env_root_dir, self.python_lib0),
472                   os.path.join(env_root_dir, self.python_lib1)
473                 ]
474             self.prepend('PYTHONPATH', l)
475
476     def load_cfg_environment(self, cfg_env):
477         """Loads environment defined in cfg_env 
478         
479         :param cfg_env Config: A config containing an environment    
480         """
481         # Loop on cfg_env values
482         for env_def in cfg_env:
483             val = cfg_env[env_def]
484             
485             # if it is env_script, do not do anything (reserved keyword)
486             if env_def == "env_script":
487                 continue
488             
489             # if it is a dict, do not do anything
490             if isinstance(val, src.pyconf.Mapping):
491                 continue
492
493             # if it is a list, loop on its values
494             if isinstance(val, src.pyconf.Sequence):
495                 # transform into list of strings
496                 l_val = []
497                 for item in val:
498                     l_val.append(item)
499                 val = l_val
500
501             # "_" means that the value must be prepended
502             if env_def.startswith("_"):
503                 # separator exception for PV_PLUGIN_PATH
504                 if env_def[1:] == 'PV_PLUGIN_PATH':
505                     self.prepend(env_def[1:], val, ';')
506                 else:
507                     self.prepend(env_def[1:], val)
508             elif env_def.endswith("_"):
509                 # separator exception for PV_PLUGIN_PATH
510                 if env_def[:-1] == 'PV_PLUGIN_PATH':
511                     self.append(env_def[:-1], val, ';')
512                 else:
513                     self.append(env_def[:-1], val)
514             else:
515                 self.set(env_def, val)
516
517     def set_a_product(self, product, logger):
518         """Sets the environment of a product. 
519         
520         :param product str: The product name
521         :param logger Logger: The logger instance to display messages
522         """
523
524         # Get the informations corresponding to the product
525         pi = src.product.get_product_config(self.cfg, product)
526         
527         if self.for_package:
528             pi.install_dir = os.path.join("out_dir_Path",
529                                           self.for_package,
530                                           pi.name)
531                     
532         # Do not define environment if the product is native
533         if src.product.product_is_native(pi):
534             return
535         
536         if not self.silent:
537             logger.write(_("Setting environment for %s\n") % product, 4)
538
539         self.add_line(1)
540         self.add_comment('setting environ for ' + product)
541         
542         # Set an additional environment for SALOME products
543         if src.product.product_is_salome(pi):
544             # set environment using definition of the product
545             self.set_salome_minimal_product_env(pi, logger)
546             self.set_salome_generic_product_env(pi)
547         
548         if src.product.product_is_cpp(pi):
549             # set a specific environment for cpp modules
550             self.set_salome_minimal_product_env(pi, logger)
551             self.set_cpp_env(pi)
552             
553             if src.product.product_is_generated(pi):
554                 if "component_name" in pi:
555                     # hack the source and install directories in order to point  
556                     # on the generated product source install directories
557                     install_dir_save = pi.install_dir
558                     source_dir_save = pi.source_dir
559                     name_save = pi.name
560                     pi.install_dir = os.path.join(self.cfg.APPLICATION.workdir,
561                                                   "INSTALL",
562                                                   pi.component_name)
563                     pi.source_dir = os.path.join(self.cfg.APPLICATION.workdir,
564                                                   "GENERATED",
565                                                   pi.component_name)
566                     pi.name = pi.component_name
567                     self.set_salome_minimal_product_env(pi, logger)
568                     self.set_salome_generic_product_env(pi)
569                     
570                     # Put original values
571                     pi.install_dir = install_dir_save
572                     pi.source_dir = source_dir_save
573                     pi.name = name_save
574         
575         # Put the environment define in the configuration of the product
576         if "environ" in pi:
577             self.load_cfg_environment(pi.environ)
578             if self.forBuild and "build" in pi.environ:
579                 self.load_cfg_environment(pi.environ.build)
580             if not self.forBuild and "launch" in pi.environ:
581                 self.load_cfg_environment(pi.environ.launch)
582             # if product_info defines a env_scripts, load it
583             if 'env_script' in pi.environ:
584                 self.run_env_script(pi, logger)
585
586         
587             
588
589     def run_env_script(self, product_info, logger=None):
590         """Runs an environment script. 
591         
592         :param product_info Config: The product description
593         :param logger Logger: The logger instance to display messages
594         """
595         env_script = product_info.environ.env_script
596         # Check that the script exists
597         if not os.path.exists(env_script):
598             raise src.SatException(_("Environment script not found: %s") % 
599                                    env_script)
600
601         if not self.silent and logger is not None:
602             logger.write("  ** load %s\n" % env_script, 4)
603
604         # import the script and run the set_env function
605         try:
606             import imp
607             pyproduct = imp.load_source(product_info.name + "_env_script",
608                                         env_script)
609             pyproduct.set_env(self, product_info.install_dir,
610                               product_info.version)
611         except:
612             __, exceptionValue, exceptionTraceback = sys.exc_info()
613             print(exceptionValue)
614             import traceback
615             traceback.print_tb(exceptionTraceback)
616             traceback.print_exc()
617
618     def run_simple_env_script(self, script_path, logger=None):
619         """Runs an environment script. Same as run_env_script, but with a 
620            script path as parameter.
621         
622         :param script_path str: a path to an environment script
623         :param logger Logger: The logger instance to display messages
624         """
625         # Check that the script exists
626         if not os.path.exists(script_path):
627             raise src.SatException(_("Environment script not found: %s") % 
628                                    script_path)
629
630         if not self.silent and logger is not None:
631             logger.write("  ** load %s\n" % script_path, 4)
632
633         script_basename = os.path.basename(script_path)
634         if script_basename.endswith(".py"):
635             script_basename = script_basename[:-len(".py")]
636
637         # import the script and run the set_env function
638         try:
639             import imp
640             pyproduct = imp.load_source(script_basename + "_env_script",
641                                         script_path)
642             pyproduct.load_env(self)
643         except:
644             __, exceptionValue, exceptionTraceback = sys.exc_info()
645             print(exceptionValue)
646             import traceback
647             traceback.print_tb(exceptionTraceback)
648             traceback.print_exc()
649
650     def set_products(self, logger, src_root=None):
651         """Sets the environment for all the products. 
652         
653         :param logger Logger: The logger instance to display messages
654         :param src_root src: the application working directory
655         """
656         self.add_line(1)
657         self.add_comment('setting environ for all products')
658
659         # Set the application working directory
660         if src_root is None:
661             src_root = self.cfg.APPLICATION.workdir
662         self.set('SRC_ROOT', src_root)
663
664         # SALOME variables
665         appli_name = "APPLI"
666         if "APPLI" in self.cfg and "application_name" in self.cfg.APPLI:
667             appli_name = self.cfg.APPLI.application_name
668         self.set("SALOME_APPLI_ROOT",
669                  os.path.join(self.cfg.APPLICATION.workdir, appli_name))
670
671         # Make sure that the python lib dirs are set after python
672         if "Python" in self.cfg.APPLICATION.products:
673             self.set_a_product("Python", logger)
674             self.set_python_libdirs()
675
676         # The loop on the products
677         for product in self.cfg.APPLICATION.products.keys():
678             if product == "Python":
679                 continue
680             self.set_a_product(product, logger)
681             self.finish(False)
682  
683     def set_full_environ(self, logger, env_info):
684         """Sets the full environment for products 
685            specified in env_info dictionary. 
686         
687         :param logger Logger: The logger instance to display messages
688         :param env_info list: the list of products
689         """
690         # set product environ
691         self.set_application_env(logger)
692
693         self.set_python_libdirs()
694
695         # set products        
696         for product in env_info:
697             self.set_a_product(product, logger)
698
699 class FileEnvWriter:
700     """Class to dump the environment to a file.
701     """
702     def __init__(self, config, logger, out_dir, src_root, env_info=None):
703         '''Initialization.
704
705         :param cfg Config: the global config
706         :param logger Logger: The logger instance to display messages
707         :param out_dir str: The directory path where t put the output files
708         :param src_root str: The application working directory
709         :param env_info str: The list of products to add in the files.
710         '''
711         self.config = config
712         self.logger = logger
713         self.out_dir = out_dir
714         self.src_root= src_root
715         self.silent = True
716         self.env_info = env_info
717
718     def write_env_file(self, filename, forBuild, shell, for_package = None):
719         """Create an environment file.
720         
721         :param filename str: the file path
722         :param forBuild bool: if true, the build environment
723         :param shell str: the type of file wanted (.sh, .bat)
724         :return: The path to the generated file
725         :rtype: str
726         """
727         if not self.silent:
728             self.logger.write(_("Create environment file %s\n") % 
729                               src.printcolors.printcLabel(filename), 3)
730
731         # create then env object
732         env_file = open(os.path.join(self.out_dir, filename), "w")
733         tmp = src.fileEnviron.get_file_environ(env_file,
734                                                shell,
735                                                {})
736         env = SalomeEnviron(self.config, tmp, forBuild, for_package=for_package)
737         env.silent = self.silent
738
739         # Set the environment
740         if self.env_info is not None:
741             env.set_full_environ(self.logger, self.env_info)
742         else:
743             # set env from the APPLICATION
744             env.set_application_env(self.logger)
745             
746             # The list of products to launch
747             lProductsName = env.get_names(self.config.APPLICATION.products.keys())
748             env.set( "SALOME_MODULES",    ','.join(lProductsName))
749             
750             # set the products
751             env.set_products(self.logger,
752                             src_root=self.src_root)
753
754         # add cleanup and close
755         env.finish(True)
756         env_file.close()
757
758         return env_file.name
759    
760     def write_cfgForPy_file(self,
761                             filename,
762                             additional_env = {},
763                             for_package = None):
764         """Append to current opened aFile a cfgForPy 
765            environment (SALOME python launcher).
766            
767         :param filename str: the file path
768         :param additional_env dict: a dictionary of additional variables 
769                                     to add to the environment
770         :param for_package str: If not None, produce a relative environment 
771                                 designed for a package. 
772         """
773         if not self.silent:
774             self.logger.write(_("Create configuration file %s\n") % 
775                               src.printcolors.printcLabel(filename.name), 3)
776
777         # create then env object
778         tmp = src.fileEnviron.get_file_environ(filename, 
779                                                "cfgForPy", 
780                                                {})
781         # environment for launch
782         env = SalomeEnviron(self.config,
783                             tmp,
784                             forBuild=False,
785                             for_package=for_package)
786         env.silent = self.silent
787
788         if self.env_info is not None:
789             env.set_full_environ(self.logger, self.env_info)
790         else:
791             # set env from PRODUCT
792             env.set_application_env(self.logger)
793
794             # The list of products to launch
795             lProductsName = env.get_names(self.config.APPLICATION.products.keys())
796             env.set( "SALOME_MODULES",    ','.join(lProductsName))
797
798             # set the products
799             env.set_products(self.logger,
800                             src_root=self.src_root)
801
802         # Add the additional environment if it is not empty
803         if len(additional_env) != 0:
804             for variable in additional_env:
805                 env.set(variable, additional_env[variable])
806
807         # add cleanup and close
808         env.finish(True)
809
810 class Shell:
811     """Definition of a Shell.
812     """
813     def __init__(self, name, extension):
814         '''Initialization.
815
816         :param name str: the shell name
817         :param extension str: the shell extension
818         '''
819         self.name = name
820         self.extension = extension
821
822 def load_environment(config, build, logger):
823     """Loads the environment (used to run the tests, for example).
824     
825     :param config Config: the global config
826     :param build bool: build environement if True
827     :param logger Logger: The logger instance to display messages
828     """
829     environ = SalomeEnviron(config, Environ(os.environ), build)
830     environ.set_application_env(logger)
831     environ.set_products(logger)
832     environ.finish(True)