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