Salome HOME
add appenPath to python2 template
[tools/sat.git] / src / fileEnviron.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 pprint as PP
21 import src.debug as DBG
22 import src.architecture
23 import src.environment
24
25 def get_file_environ(output, shell, environ=None):
26     """Instantiate correct FileEnvironment sub-class.
27     
28     :param output file: the output file stream.
29     :param shell str: the type of shell syntax to use.
30     :param environ dict: a potential additional environment.
31     """
32     if environ == None:
33         environ=src.environment.Environ({})
34     if shell == "bash":
35         return BashFileEnviron(output, environ)
36     if shell == "tcl":
37         return TclFileEnviron(output, environ)
38     if shell == "bat":
39         return BatFileEnviron(output, environ)
40     if shell == "cfgForPy":
41         return LauncherFileEnviron(output, environ)
42     if shell == "cfg":
43         return ContextFileEnviron(output, environ)
44     raise Exception("FileEnviron: Unknown shell = %s" % shell)
45
46 class FileEnviron(object):
47     """\
48     Base class for shell environment
49     """
50     def __init__(self, output, environ=None):
51         """\
52         Initialization
53         
54         :param output file: the output file stream.
55         :param environ dict: SalomeEnviron.
56         """
57         self._do_init(output, environ)
58
59     def __repr__(self):
60         """\
61         easy non exhaustive quick resume for debug print"""
62         res = {
63           "output" : self.output,
64           "environ" : self.environ,
65         }
66         return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
67         
68
69     def _do_init(self, output, environ=None):
70         """\
71         Initialization
72         
73         :param output file: the output file stream.
74         :param environ dict: a potential additional environment.
75         """
76         self.output = output
77         self.init_path=True # by default we initialise all paths, except PATH
78         if environ is not None:
79             self.environ = environ
80         else:
81             self.environ = src.environment.Environ({})
82
83     def add_line(self, number):
84         """\
85         Add some empty lines in the shell file
86         
87         :param number int: the number of lines to add
88         """
89         self.output.write("\n" * number)
90
91     def add_comment(self, comment):
92         """\
93         Add a comment in the shell file
94         
95         :param comment str: the comment to add
96         """
97         self.output.write("# %s\n" % comment)
98
99     def add_echo(self, text):
100         """\
101         Add a "echo" in the shell file
102         
103         :param text str: the text to echo
104         """
105         self.output.write('echo %s"\n' % text)
106
107     def add_warning(self, warning):
108         """\
109         Add a warning "echo" in the shell file
110         
111         :param warning str: the text to echo
112         """
113         self.output.write('echo "WARNING %s"\n' % warning)
114
115     def append_value(self, key, value, sep=os.pathsep):
116         """\
117         append value to key using sep,
118         if value contains ":" or ";" then raise error
119
120         :param key str: the environment variable to append
121         :param value str: the value to append to key
122         :param sep str: the separator string
123         """
124         # check that value so no contain the system separator
125         separator=os.pathsep
126         if separator in value:
127             raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
128         do_append=True
129         if self.environ.is_defined(key):
130             value_list = self.environ.get(key).split(sep)
131             if self.environ._expandvars(value) in value_list:
132                 do_append=False  # value is already in key path : we don't append it again
133             
134         if do_append:
135             self.environ.append_value(key, value,sep)
136             self.set(key, self.get(key) + sep + value)
137
138     def append(self, key, value, sep=os.pathsep):
139         """\
140         Same as append_value but the value argument can be a list
141         
142         :param key str: the environment variable to append
143         :param value str or list: the value(s) to append to key
144         :param sep str: the separator string
145         """
146         if isinstance(value, list):
147             for v in value:
148                 self.append_value(key, v, sep)
149         else:
150             self.append_value(key, value, sep)
151
152     def prepend_value(self, key, value, sep=os.pathsep):
153         """\
154         prepend value to key using sep,
155         if value contains ":" or ";" then raise error
156         
157         :param key str: the environment variable to prepend
158         :param value str: the value to prepend to key
159         :param sep str: the separator string
160         """
161         # check that value so no contain the system separator
162         separator=os.pathsep
163         if separator in value:
164             raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
165
166         do_not_prepend=False
167         if self.environ.is_defined(key):
168             value_list = self.environ.get(key).split(sep)
169             exp_val=self.environ._expandvars(value)
170             if exp_val in value_list:
171                 do_not_prepend=True
172         if not do_not_prepend:
173             self.environ.prepend_value(key, value,sep)
174             self.set(key, value + sep + self.get(key))
175
176     def prepend(self, key, value, sep=os.pathsep):
177         """\
178         Same as prepend_value but the value argument can be a list
179         
180         :param key str: the environment variable to prepend
181         :param value str or list: the value(s) to prepend to key
182         :param sep str: the separator string
183         """
184         if isinstance(value, list):
185             for v in reversed(value): # prepend list, first item at last to stay first
186                 self.prepend_value(key, v, sep)
187         else:
188             self.prepend_value(key, value, sep)
189
190     def is_defined(self, key):
191         """\
192         Check if the key exists in the environment
193         
194         :param key str: the environment variable to check
195         """
196         return self.environ.is_defined(key)
197
198     def set(self, key, value):
199         """\
200         Set the environment variable 'key' to value 'value'
201         
202         :param key str: the environment variable to set
203         :param value str: the value
204         """
205         raise NotImplementedError("set is not implement for this shell!")
206
207     def get(self, key):
208         """\
209         Get the value of the environment variable "key"
210         
211         :param key str: the environment variable
212         """
213         return '${%s}' % key
214
215     def get_value(self, key):
216         """Get the real value of the environment variable "key"
217         It can help env scripts
218         :param key str: the environment variable
219         """
220         return self.environ.get_value(key)
221
222     def finish(self):
223         """Add a final instruction in the out file (in case of file generation)
224         
225         :param required bool: Do nothing if required is False
226         """
227         return
228
229     def set_no_init_path(self):
230         """Set the no initialisation mode for all paths.
231            By default only PATH is not reinitialised. All others paths are
232            (LD_LIBRARY_PATH, PYTHONPATH, ...)
233            After the call to these function ALL PATHS ARE NOT REINITIALISED.
234            There initial value is inherited from the environment
235         """
236         self.init_path=False
237
238     def value_filter(self, value):
239         res=value
240         # on windows platform, replace / by \
241         if src.architecture.is_windows():
242             res = value.replace("/","\\")
243         return res
244
245
246 class TclFileEnviron(FileEnviron):
247     """\
248     Class for tcl shell.
249     """
250     def __init__(self, output, environ=None):
251         """Initialization
252         
253         :param output file: the output file stream.
254         :param environ dict: a potential additional environment.
255         """
256         self._do_init(output, environ)
257         self.output.write(tcl_header.replace("<module_name>",
258                                              self.environ.get("sat_product_name")))
259         self.output.write("\nset software %s\n" % self.environ.get("sat_product_name") )
260         self.output.write("set version %s\n" % self.environ.get("sat_product_version") )
261         root=os.path.join(self.environ.get("sat_product_base_path"),  
262                                   "apps", 
263                                   self.environ.get("sat_product_base_name"), 
264                                   "$software", 
265                                   "$version")
266         self.output.write("set root %s\n" % root) 
267         modules_to_load=self.environ.get("sat_product_load_depend")
268         if len(modules_to_load)>0:
269             # write module load commands for product dependencies
270             self.output.write("\n")
271             for module_to_load in modules_to_load.split(";"):
272                 self.output.write(module_to_load+"\n")
273
274     def set(self, key, value):
275         """Set the environment variable "key" to value "value"
276         
277         :param key str: the environment variable to set
278         :param value str: the value
279         """
280         self.output.write('setenv  %s "%s"\n' % (key, value))
281         self.environ.set(key, value)
282         
283     def get(self, key):
284         """\
285         Get the value of the environment variable "key"
286         
287         :param key str: the environment variable
288         """
289         return self.environ.get(key)
290
291     def append_value(self, key, value, sep=os.pathsep):
292         """append value to key using sep
293         
294         :param key str: the environment variable to append
295         :param value str: the value to append to key
296         :param sep str: the separator string
297         """
298         if sep==os.pathsep:
299             self.output.write('append-path  %s   %s\n' % (key, value))
300         else:
301             self.output.write('append-path --delim=\%c %s   %s\n' % (sep, key, value))
302
303     def prepend_value(self, key, value, sep=os.pathsep):
304         """prepend value to key using sep
305         
306         :param key str: the environment variable to prepend
307         :param value str: the value to prepend to key
308         :param sep str: the separator string
309         """
310         if sep==os.pathsep:
311             self.output.write('prepend-path  %s   %s\n' % (key, value))
312         else:
313             self.output.write('prepend-path --delim=\%c %s   %s\n' % (sep, key, value))
314
315         
316 class BashFileEnviron(FileEnviron):
317     """\
318     Class for bash shell.
319     """
320     def __init__(self, output, environ=None):
321         """Initialization
322         
323         :param output file: the output file stream.
324         :param environ dict: a potential additional environment.
325         """
326         self._do_init(output, environ)
327         self.output.write(bash_header)
328
329     def set(self, key, value):
330         """Set the environment variable "key" to value "value"
331         
332         :param key str: the environment variable to set
333         :param value str: the value
334         """
335         self.output.write('export %s="%s"\n' % (key, value))
336         self.environ.set(key, value)
337         
338
339         
340 class BatFileEnviron(FileEnviron):
341     """\
342     for Windows batch shell.
343     """
344     def __init__(self, output, environ=None):
345         """Initialization
346         
347         :param output file: the output file stream.
348         :param environ dict: a potential additional environment.
349         """
350         self._do_init(output, environ)
351         self.output.write(bat_header)
352
353     def add_comment(self, comment):
354         """Add a comment in the shell file
355         
356         :param comment str: the comment to add
357         """
358         self.output.write("rem %s\n" % comment)
359     
360     def get(self, key):
361         """Get the value of the environment variable "key"
362         
363         :param key str: the environment variable
364         """
365         return '%%%s%%' % key
366     
367     def set(self, key, value):
368         """Set the environment variable "key" to value "value"
369         
370         :param key str: the environment variable to set
371         :param value str: the value
372         """
373         self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
374         self.environ.set(key, value)
375
376
377 class ContextFileEnviron(FileEnviron):
378     """Class for a salome context configuration file.
379     """
380     def __init__(self, output, environ=None):
381         """Initialization
382         
383         :param output file: the output file stream.
384         :param environ dict: a potential additional environment.
385         """
386         self._do_init(output, environ)
387         self.output.write(cfg_header)
388
389     def set(self, key, value):
390         """Set the environment variable "key" to value "value"
391         
392         :param key str: the environment variable to set
393         :param value str: the value
394         """
395         self.output.write('%s="%s"\n' % (key, value))
396         self.environ.set(key, value)
397
398     def get(self, key):
399         """Get the value of the environment variable "key"
400         
401         :param key str: the environment variable
402         """
403         return '%({0})s'.format(key)
404
405     def add_echo(self, text):
406         """Add a comment
407         
408         :param text str: the comment to add
409         """
410         self.add_comment(text)
411
412     def add_warning(self, warning):
413         """Add a warning
414         
415         :param text str: the warning to add
416         """
417         self.add_comment("WARNING %s"  % warning)
418
419     def prepend_value(self, key, value, sep=os.pathsep):
420         """prepend value to key using sep
421         
422         :param key str: the environment variable to prepend
423         :param value str: the value to prepend to key
424         :param sep str: the separator string
425         """
426         do_append=True
427         if self.environ.is_defined(key):
428             value_list = self.environ.get(key).split(sep)
429             #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
430             if value in value_list:
431                 do_append=False  # value is already in key path : we don't append it again
432             
433         if do_append:
434             self.environ.append_value(key, value,sep)
435             self.output.write('ADD_TO_%s: %s\n' % (key, value))
436
437     def append_value(self, key, value, sep=os.pathsep):
438         """append value to key using sep
439         
440         :param key str: the environment variable to append
441         :param value str: the value to append to key
442         :param sep str: the separator string
443         """
444         self.prepend_value(key, value)
445
446
447 class LauncherFileEnviron(FileEnviron):
448     """\
449     Class to generate a launcher file script 
450     (in python syntax) SalomeContext API
451     """
452     def __init__(self, output, environ=None):
453         """Initialization
454         
455         :param output file: the output file stream.
456         :param environ dict: a potential additional environment.
457         """
458         self._do_init(output, environ)
459         self.python_version=self.environ.get("sat_python_version")
460         self.bin_kernel_root_dir=self.environ.get("sat_bin_kernel_install_dir")
461         self.app_root_dir=self.environ.get("sat_app_root_dir")
462
463         # four whitespaces for first indentation in a python script
464         self.indent="    "
465         self.prefix="context."
466         self.setVarEnv="setVariable"
467         self.begin=self.indent+self.prefix
468
469         # write the begining of launcher file.
470         # choose the template version corresponding to python version 
471         # and substitute BIN_KERNEL_INSTALL_DIR (the path to salomeContext.py)
472         if self.python_version == 2:
473             launcher_header=launcher_header2
474         else:
475             launcher_header=launcher_header3
476         self.output.write(launcher_header\
477                           .replace("BIN_KERNEL_INSTALL_DIR", self.bin_kernel_root_dir))
478
479         # for these path, we use specialired functions in salomeContext api
480         self.specialKeys={"PATH": "Path",
481                           "LD_LIBRARY_PATH": "LdLibraryPath",
482                           "PYTHONPATH": "PythonPath"}
483
484         # we do not want to reinitialise PATH.
485         # for that we make sure PATH is in self.environ
486         # and therefore we will not use setVariable for PATH
487         if not self.environ.is_defined("PATH"):
488             self.environ.set("PATH","")
489
490
491     def add_echo(self, text):
492         """Add a comment
493         
494         :param text str: the comment to add
495         """
496         self.output.write('# %s"\n' % text)
497
498     def add_warning(self, warning):
499         """Add a warning
500         
501         :param text str: the warning to add
502         """
503         self.output.write('# "WARNING %s"\n' % warning)
504
505     def append_value(self, key, value, sep=os.pathsep):
506         """append value to key using sep,
507         if value contains ":" or ";" then raise error
508         
509         :param key str: the environment variable to prepend
510         :param value str: the value to prepend to key
511         :param sep str: the separator string
512         """
513         # check that value so no contain the system separator
514         separator=os.pathsep
515         msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
516         if separator in value:
517             raise Exception(msg % (key, value, separator))
518
519         if (self.init_path and (not self.environ.is_defined(key))):
520             # reinitialisation mode set to true (the default)
521             # for the first occurrence of key, we set it.
522             # therefore key will not be inherited from environment
523             self.set(key, value)
524             return
525
526         # in all other cases we use append (except if value is already the key
527         do_append=True
528         if self.environ.is_defined(key):
529             value_list = self.environ.get(key).split(sep)
530             # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
531             if value in value_list:
532                 do_append=False  # value is already in key path : we don't append it again
533             
534         if do_append:
535             self.environ.append_value(key, value,sep) # register value in self.environ
536             if key in self.specialKeys.keys():
537                 #for these special keys we use the specific salomeContext function
538                 self.output.write(self.begin+'addTo%s(r"%s")\n' % 
539                                   (self.specialKeys[key], self.value_filter(value)))
540             else:
541                 # else we use the general salomeContext addToVariable function
542                 self.output.write(self.indent+'appendPath(r"%s", r"%s",separator="%s")\n' 
543                                   % (key, self.value_filter(value), sep))
544
545     def append(self, key, value, sep=":"):
546         """Same as append_value but the value argument can be a list
547         
548         :param key str: the environment variable to append
549         :param value str or list: the value(s) to append to key
550         :param sep str: the separator string
551         """
552         if isinstance(value, list):
553             for v in value:
554                 self.append_value(key, v, sep)
555         else:
556             self.append_value(key, value, sep)
557
558     def prepend_value(self, key, value, sep=os.pathsep):
559         """prepend value to key using sep,
560         if value contains ":" or ";" then raise error
561         
562         :param key str: the environment variable to prepend
563         :param value str: the value to prepend to key
564         :param sep str: the separator string
565         """
566         # check that value so no contain the system separator
567         separator=os.pathsep
568         msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
569         if separator in value:
570             raise Exception(msg % (key, value, separator))
571
572         if (self.init_path and (not self.environ.is_defined(key))):
573             # reinitialisation mode set to true (the default)
574             # for the first occurrence of key, we set it.
575             # therefore key will not be inherited from environment
576             self.set(key, value)
577             return
578         # in all other cases we use append (except if value is already the key
579         do_append=True
580         if self.environ.is_defined(key):
581             value_list = self.environ.get(key).split(sep)
582             # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
583             if value in value_list:
584                 do_append=False  # value is already in key path : we don't append it again
585             
586         if do_append:
587             self.environ.append_value(key, value,sep) # register value in self.environ
588             if key in self.specialKeys.keys():
589                 #for these special keys we use the specific salomeContext function
590                 self.output.write(self.begin+'addTo%s(r"%s")\n' % 
591                                   (self.specialKeys[key], self.value_filter(value)))
592             else:
593                 # else we use the general salomeContext addToVariable function
594                 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n' 
595                                   % (key, self.value_filter(value), sep))
596             
597
598     def prepend(self, key, value, sep=":"):
599         """Same as prepend_value but the value argument can be a list
600         
601         :param key str: the environment variable to prepend
602         :param value str or list: the value(s) to prepend to key
603         :param sep str: the separator string
604         """
605         if isinstance(value, list):
606             for v in value:
607                 self.prepend_value(key, v, sep)
608         else:
609             self.prepend_value(key, value, sep)
610
611
612     def set(self, key, value):
613         """Set the environment variable "key" to value "value"
614         
615         :param key str: the environment variable to set
616         :param value str: the value
617         """
618         self.output.write(self.begin+self.setVarEnv+
619                           '(r"%s", r"%s", overwrite=True)\n' % 
620                           (key, self.value_filter(value)))
621         self.environ.set(key,value)
622     
623
624     def add_comment(self, comment):
625         # Special comment in case of the distène licence
626         if comment=="DISTENE license":
627             self.output.write(self.indent+
628                               "#"+
629                               self.prefix+
630                               self.setVarEnv+
631                               '(r"%s", r"%s", overwrite=True)\n' % 
632                               ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
633             self.output.write(self.indent+
634                               "#"+
635                               self.prefix+
636                               self.setVarEnv+
637                               '(r"%s", r"%s", overwrite=True)\n' % 
638                               ('DLIM8VAR', '<your licence>'))
639             return
640         if "setting environ for" in comment:
641             self.output.write(self.indent+"#[%s]\n" % 
642                               comment.split("setting environ for ")[1])
643             return
644
645         self.output.write(self.indent+"# %s\n" % comment)
646
647     def finish(self):
648         """\
649         Add a final instruction in the out file (in case of file generation)
650         In the particular launcher case, do nothing
651         
652         :param required bool: Do nothing if required is False
653         """
654         if self.python_version == 2:
655             launcher_tail=launcher_tail_py2
656         else:
657             launcher_tail=launcher_tail_py3
658         self.output.write(launcher_tail)
659         return
660
661 class ScreenEnviron(FileEnviron):
662     def __init__(self, output, environ=None):
663         self._do_init(output, environ)
664         self.defined = {}
665
666     def add_line(self, number):
667         pass
668
669     def add_comment(self, comment):
670         pass
671
672     def add_echo(self, text):
673         pass
674
675     def add_warning(self, warning):
676         pass
677
678     def write(self, command, name, value, sign="="):
679         import src
680         self.output.write("  %s%s %s %s %s\n" % \
681             (src.printcolors.printcLabel(command),
682              " " * (12 - len(command)),
683              src.printcolors.printcInfo(name), sign, value))
684
685     def is_defined(self, name):
686         return name in self.defined
687
688     def get(self, name):
689         return "${%s}" % name
690
691     def set(self, name, value):
692         self.write("set", name, value)
693         self.defined[name] = value
694
695     def prepend(self, name, value, sep=":"):
696         if isinstance(value, list):
697             value = sep.join(value)
698         value = value + sep + self.get(name)
699         self.write("prepend", name, value)
700
701     def append(self, name, value, sep=":"):
702         if isinstance(value, list):
703             value = sep.join(value)
704         value = self.get(name) + sep + value
705         self.write("append", name, value)
706
707     def run_env_script(self, module, script):
708         self.write("load", script, "", sign="")
709
710
711 #
712 #  Headers
713 #
714 bat_header="""\
715 @echo off
716
717 rem The following variables are used only in case of a sat package
718 set out_dir_Path=%~dp0
719 """
720
721 tcl_header="""\
722 #%Module -*- tcl -*-
723 #
724 # <module_name> module for use with 'environment-modules' package
725 #
726 """
727
728 bash_header="""\
729 #!/bin/bash
730 ##########################################################################
731 #
732 # This line is used only in case of a sat package
733 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
734
735 ###########################################################################
736 """
737
738 cfg_header="""\
739 [SALOME Configuration]
740 """
741
742 launcher_header2="""\
743 #! /usr/bin/env python
744
745 ################################################################
746 # WARNING: this file is automatically generated by SalomeTools #
747 # WARNING: and so could be overwritten at any time.            #
748 ################################################################
749
750 import os
751 import sys
752 import subprocess
753
754
755 # Add the pwdPath to able to run the launcher after unpacking a package
756 # Used only in case of a salomeTools package
757 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
758
759 # Preliminary work to initialize path to SALOME Python modules
760 def __initialize():
761
762   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]  # to get salomeContext
763   
764   # define folder to store omniorb config (initially in virtual application folder)
765   try:
766     from salomeContextUtils import setOmniOrbUserPath
767     setOmniOrbUserPath()
768   except Exception as e:
769     print(e)
770     sys.exit(1)
771 # End of preliminary work
772
773 # salome doc only works for virtual applications. Therefore we overwrite it with this function
774 def _showDoc(modules):
775     for module in modules:
776       modulePath = os.getenv(module+"_ROOT_DIR")
777       if modulePath != None:
778         baseDir = os.path.join(modulePath, "share", "doc", "salome")
779         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
780         if not os.path.isfile(docfile):
781           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
782         if not os.path.isfile(docfile):
783           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
784         if os.path.isfile(docfile):
785           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
786         else:
787           print ("Online documentation is not accessible for module:", module)
788       else:
789         print (module+"_ROOT_DIR not found!")
790
791 def main(args):
792   # Identify application path then locate configuration files
793   __initialize()
794
795   if args == ['--help']:
796     from salomeContext import usage
797     usage()
798     sys.exit(0)
799
800
801   # Create a SalomeContext which parses configFileNames to initialize environment
802   try:
803     from salomeContext import SalomeContext, SalomeContextException
804     context = SalomeContext(None)
805     
806     # Here set specific variables, if needed
807     # context.addToPath('mypath')
808     # context.addToLdLibraryPath('myldlibrarypath')
809     # context.addToPythonPath('mypythonpath')
810     # context.setVariable('myvarname', 'value')
811
812     # Logger level error
813     context.getLogger().setLevel(40)
814 """
815
816 launcher_header3="""\
817 #! /usr/bin/env python3
818
819 ################################################################
820 # WARNING: this file is automatically generated by SalomeTools #
821 # WARNING: and so could be overwritten at any time.            #
822 ################################################################
823
824 import os
825 import sys
826 import subprocess
827
828
829 # Add the pwdPath to able to run the launcher after unpacking a package
830 # Used only in case of a salomeTools package
831 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
832
833 # Preliminary work to initialize path to SALOME Python modules
834 def __initialize():
835
836   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
837   
838   # define folder to store omniorb config (initially in virtual application folder)
839   try:
840     from salomeContextUtils import setOmniOrbUserPath
841     setOmniOrbUserPath()
842   except Exception as e:
843     print(e)
844     sys.exit(1)
845 # End of preliminary work
846
847 # salome doc only works for virtual applications. Therefore we overwrite it with this function
848 def _showDoc(modules):
849     for module in modules:
850       modulePath = os.getenv(module+"_ROOT_DIR")
851       if modulePath != None:
852         baseDir = os.path.join(modulePath, "share", "doc", "salome")
853         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
854         if not os.path.isfile(docfile):
855           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
856         if not os.path.isfile(docfile):
857           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
858         if os.path.isfile(docfile):
859           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
860         else:
861           print("Online documentation is not accessible for module:", module)
862       else:
863         print(module+"_ROOT_DIR not found!")
864
865 def main(args):
866   # Identify application path then locate configuration files
867   __initialize()
868
869   if args == ['--help']:
870     from salomeContext import usage
871     usage()
872     sys.exit(0)
873
874   #from salomeContextUtils import getConfigFileNames
875   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
876   #if len(unexisting) > 0:
877   #  print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
878   #  sys.exit(1)
879
880   # Create a SalomeContext which parses configFileNames to initialize environment
881   try:
882     from salomeContext import SalomeContext, SalomeContextException
883     context = SalomeContext(None)
884     
885     # Here set specific variables, if needed
886     # context.addToPath('mypath')
887     # context.addToLdLibraryPath('myldlibrarypath')
888     # context.addToPythonPath('mypythonpath')
889     # context.setVariable('myvarname', 'value')
890
891     # Logger level error
892     context.getLogger().setLevel(40)
893 """
894
895 launcher_tail_py2="""\
896     if len(args) >1 and args[0]=='doc':
897         _showDoc(args[1:])
898         return
899
900     # Start SALOME, parsing command line arguments
901     out, err, status = context.runSalome(args)
902     sys.exit(status)
903
904   except SalomeContextException, e:
905     import logging
906     logging.getLogger("salome").error(e)
907     sys.exit(1)
908 #
909 # salomeContext only prepend variables, we use our own appendPath when required
910 def appendPath(name, value, separator=os.pathsep):
911     if value == '':
912       return
913
914     value = os.path.expandvars(value) # expand environment variables
915     env = os.getenv(name, None)
916     if env is None:
917       os.environ[name] = value
918     else:
919       os.environ[name] = env + separator + value
920
921
922 if __name__ == "__main__":
923   args = sys.argv[1:]
924   main(args)
925 #
926 """
927
928 launcher_tail_py3="""\
929     if len(args) >1 and args[0]=='doc':
930         _showDoc(args[1:])
931         return
932
933     # Start SALOME, parsing command line arguments
934     out, err, status = context.runSalome(args)
935     sys.exit(status)
936
937   except SalomeContextException as e:
938     import logging
939     logging.getLogger("salome").error(e)
940     sys.exit(1)
941  
942 # salomeContext only prepend variables, we use our own appendPath when required
943 def appendPath(name, value, separator=os.pathsep):
944     if value == '':
945       return
946
947     value = os.path.expandvars(value) # expand environment variables
948     env = os.getenv(name, None)
949     if env is None:
950       os.environ[name] = value
951     else:
952       os.environ[name] = env + separator + value
953
954
955 if __name__ == "__main__":
956   args = sys.argv[1:]
957   main(args)
958 #
959 """
960     
961