Salome HOME
sat #17833 : nouveau mode pour les bases compatible avec environment module
[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         #print "CNC TclFileEnviron set ", key, " to ", value
281         self.output.write('setenv  %s "%s"\n' % (key, value))
282         self.environ.set(key, value)
283         
284     def get(self, key):
285         """\
286         Get the value of the environment variable "key"
287         
288         :param key str: the environment variable
289         """
290         return self.environ.get(key)
291
292     def append_value(self, key, value, sep=os.pathsep):
293         """append value to key using sep
294         
295         :param key str: the environment variable to append
296         :param value str: the value to append to key
297         :param sep str: the separator string
298         """
299         if sep==os.pathsep:
300             self.output.write('append-path  %s   %s\n' % (key, value))
301         else:
302             self.output.write('append-path --delim=\%c %s   %s\n' % (sep, key, value))
303
304     def prepend_value(self, key, value, sep=os.pathsep):
305         """prepend value to key using sep
306         
307         :param key str: the environment variable to prepend
308         :param value str: the value to prepend to key
309         :param sep str: the separator string
310         """
311         if sep==os.pathsep:
312             self.output.write('prepend-path  %s   %s\n' % (key, value))
313         else:
314             self.output.write('prepend-path --delim=\%c %s   %s\n' % (sep, key, value))
315
316         
317 class BashFileEnviron(FileEnviron):
318     """\
319     Class for bash shell.
320     """
321     def __init__(self, output, environ=None):
322         """Initialization
323         
324         :param output file: the output file stream.
325         :param environ dict: a potential additional environment.
326         """
327         self._do_init(output, environ)
328         self.output.write(bash_header)
329
330     def set(self, key, value):
331         """Set the environment variable "key" to value "value"
332         
333         :param key str: the environment variable to set
334         :param value str: the value
335         """
336         self.output.write('export %s="%s"\n' % (key, value))
337         self.environ.set(key, value)
338         
339
340         
341 class BatFileEnviron(FileEnviron):
342     """\
343     for Windows batch shell.
344     """
345     def __init__(self, output, environ=None):
346         """Initialization
347         
348         :param output file: the output file stream.
349         :param environ dict: a potential additional environment.
350         """
351         self._do_init(output, environ)
352         self.output.write(bat_header)
353
354     def add_comment(self, comment):
355         """Add a comment in the shell file
356         
357         :param comment str: the comment to add
358         """
359         self.output.write("rem %s\n" % comment)
360     
361     def get(self, key):
362         """Get the value of the environment variable "key"
363         
364         :param key str: the environment variable
365         """
366         return '%%%s%%' % key
367     
368     def set(self, key, value):
369         """Set the environment variable "key" to value "value"
370         
371         :param key str: the environment variable to set
372         :param value str: the value
373         """
374         self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
375         self.environ.set(key, value)
376
377
378 class ContextFileEnviron(FileEnviron):
379     """Class for a salome context configuration file.
380     """
381     def __init__(self, output, environ=None):
382         """Initialization
383         
384         :param output file: the output file stream.
385         :param environ dict: a potential additional environment.
386         """
387         self._do_init(output, environ)
388         self.output.write(cfg_header)
389
390     def set(self, key, value):
391         """Set the environment variable "key" to value "value"
392         
393         :param key str: the environment variable to set
394         :param value str: the value
395         """
396         self.output.write('%s="%s"\n' % (key, value))
397         self.environ.set(key, value)
398
399     def get(self, key):
400         """Get the value of the environment variable "key"
401         
402         :param key str: the environment variable
403         """
404         return '%({0})s'.format(key)
405
406     def add_echo(self, text):
407         """Add a comment
408         
409         :param text str: the comment to add
410         """
411         self.add_comment(text)
412
413     def add_warning(self, warning):
414         """Add a warning
415         
416         :param text str: the warning to add
417         """
418         self.add_comment("WARNING %s"  % warning)
419
420     def prepend_value(self, key, value, sep=os.pathsep):
421         """prepend value to key using sep
422         
423         :param key str: the environment variable to prepend
424         :param value str: the value to prepend to key
425         :param sep str: the separator string
426         """
427         do_append=True
428         if self.environ.is_defined(key):
429             value_list = self.environ.get(key).split(sep)
430             #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
431             if value in value_list:
432                 do_append=False  # value is already in key path : we don't append it again
433             
434         if do_append:
435             self.environ.append_value(key, value,sep)
436             self.output.write('ADD_TO_%s: %s\n' % (key, value))
437
438     def append_value(self, key, value, sep=os.pathsep):
439         """append value to key using sep
440         
441         :param key str: the environment variable to append
442         :param value str: the value to append to key
443         :param sep str: the separator string
444         """
445         self.prepend_value(key, value)
446
447
448 class LauncherFileEnviron(FileEnviron):
449     """\
450     Class to generate a launcher file script 
451     (in python syntax) SalomeContext API
452     """
453     def __init__(self, output, environ=None):
454         """Initialization
455         
456         :param output file: the output file stream.
457         :param environ dict: a potential additional environment.
458         """
459         self._do_init(output, environ)
460         self.python_version=self.environ.get("sat_python_version")
461         self.bin_kernel_root_dir=self.environ.get("sat_bin_kernel_install_dir")
462         self.app_root_dir=self.environ.get("sat_app_root_dir")
463
464         # four whitespaces for first indentation in a python script
465         self.indent="    "
466         self.prefix="context."
467         self.setVarEnv="setVariable"
468         self.begin=self.indent+self.prefix
469
470         # write the begining of launcher file.
471         # choose the template version corresponding to python version 
472         # and substitute BIN_KERNEL_INSTALL_DIR (the path to salomeContext.py)
473         if self.python_version == 2:
474             launcher_header=launcher_header2
475         else:
476             launcher_header=launcher_header3
477         self.output.write(launcher_header\
478                           .replace("BIN_KERNEL_INSTALL_DIR", self.bin_kernel_root_dir))
479
480         # for these path, we use specialired functions in salomeContext api
481         self.specialKeys={"PATH": "Path",
482                           "LD_LIBRARY_PATH": "LdLibraryPath",
483                           "PYTHONPATH": "PythonPath"}
484
485         # we do not want to reinitialise PATH.
486         # for that we make sure PATH is in self.environ
487         # and therefore we will not use setVariable for PATH
488         if not self.environ.is_defined("PATH"):
489             self.environ.set("PATH","")
490
491
492     def add_echo(self, text):
493         """Add a comment
494         
495         :param text str: the comment to add
496         """
497         self.output.write('# %s"\n' % text)
498
499     def add_warning(self, warning):
500         """Add a warning
501         
502         :param text str: the warning to add
503         """
504         self.output.write('# "WARNING %s"\n' % warning)
505
506     def append_value(self, key, value, sep=":"):
507         """append value to key using sep,
508         if value contains ":" or ";" then raise error
509         
510         :param key str: the environment variable to append
511         :param value str: the value to append to key
512         :param sep str: the separator string
513         """
514         # append is not defined in context api
515         self.prepend_value(key, value)
516
517     def append(self, key, value, sep=":"):
518         """Same as append_value but the value argument can be a list
519         
520         :param key str: the environment variable to append
521         :param value str or list: the value(s) to append to key
522         :param sep str: the separator string
523         """
524         if isinstance(value, list):
525             for v in value:
526                 self.append_value(key, v, sep)
527         else:
528             self.append_value(key, value, sep)
529
530     def prepend_value(self, key, value, sep=os.pathsep):
531         """prepend value to key using sep,
532         if value contains ":" or ";" then raise error
533         
534         :param key str: the environment variable to prepend
535         :param value str: the value to prepend to key
536         :param sep str: the separator string
537         """
538         # check that value so no contain the system separator
539         separator=os.pathsep
540         msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
541         if separator in value:
542             raise Exception(msg % (key, value, separator))
543
544         if (self.init_path and (not self.environ.is_defined(key))):
545             # reinitialisation mode set to true (the default)
546             # for the first occurrence of key, we set it.
547             # therefore key will not be inherited from environment
548             self.set(key, value)
549             return
550         # in all other cases we use append (except if value is already the key
551         do_append=True
552         if self.environ.is_defined(key):
553             value_list = self.environ.get(key).split(sep)
554             # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
555             if value in value_list:
556                 do_append=False  # value is already in key path : we don't append it again
557             
558         if do_append:
559             self.environ.append_value(key, value,sep) # register value in self.environ
560             if key in self.specialKeys.keys():
561                 #for these special keys we use the specific salomeContext function
562                 self.output.write(self.begin+'addTo%s(r"%s")\n' % 
563                                   (self.specialKeys[key], self.value_filter(value)))
564             else:
565                 # else we use the general salomeContext addToVariable function
566                 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n' 
567                                   % (key, self.value_filter(value), sep))
568             
569
570     def prepend(self, key, value, sep=":"):
571         """Same as prepend_value but the value argument can be a list
572         
573         :param key str: the environment variable to prepend
574         :param value str or list: the value(s) to prepend to key
575         :param sep str: the separator string
576         """
577         if isinstance(value, list):
578             for v in value:
579                 self.prepend_value(key, v, sep)
580         else:
581             self.prepend_value(key, value, sep)
582
583
584     def set(self, key, value):
585         """Set the environment variable "key" to value "value"
586         
587         :param key str: the environment variable to set
588         :param value str: the value
589         """
590         self.output.write(self.begin+self.setVarEnv+
591                           '(r"%s", r"%s", overwrite=True)\n' % 
592                           (key, self.value_filter(value)))
593         self.environ.set(key,value)
594     
595
596     def add_comment(self, comment):
597         # Special comment in case of the distène licence
598         if comment=="DISTENE license":
599             self.output.write(self.indent+
600                               "#"+
601                               self.prefix+
602                               self.setVarEnv+
603                               '(r"%s", r"%s", overwrite=True)\n' % 
604                               ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
605             self.output.write(self.indent+
606                               "#"+
607                               self.prefix+
608                               self.setVarEnv+
609                               '(r"%s", r"%s", overwrite=True)\n' % 
610                               ('DLIM8VAR', '<your licence>'))
611             return
612         if "setting environ for" in comment:
613             self.output.write(self.indent+"#[%s]\n" % 
614                               comment.split("setting environ for ")[1])
615             return
616
617         self.output.write(self.indent+"# %s\n" % comment)
618
619     def finish(self):
620         """\
621         Add a final instruction in the out file (in case of file generation)
622         In the particular launcher case, do nothing
623         
624         :param required bool: Do nothing if required is False
625         """
626         if self.python_version == 2:
627             launcher_tail=launcher_tail_py2
628         else:
629             launcher_tail=launcher_tail_py3
630         self.output.write(launcher_tail)
631         return
632
633 class ScreenEnviron(FileEnviron):
634     def __init__(self, output, environ=None):
635         self._do_init(output, environ)
636         self.defined = {}
637
638     def add_line(self, number):
639         pass
640
641     def add_comment(self, comment):
642         pass
643
644     def add_echo(self, text):
645         pass
646
647     def add_warning(self, warning):
648         pass
649
650     def write(self, command, name, value, sign="="):
651         import src
652         self.output.write("  %s%s %s %s %s\n" % \
653             (src.printcolors.printcLabel(command),
654              " " * (12 - len(command)),
655              src.printcolors.printcInfo(name), sign, value))
656
657     def is_defined(self, name):
658         return name in self.defined
659
660     def get(self, name):
661         return "${%s}" % name
662
663     def set(self, name, value):
664         self.write("set", name, value)
665         self.defined[name] = value
666
667     def prepend(self, name, value, sep=":"):
668         if isinstance(value, list):
669             value = sep.join(value)
670         value = value + sep + self.get(name)
671         self.write("prepend", name, value)
672
673     def append(self, name, value, sep=":"):
674         if isinstance(value, list):
675             value = sep.join(value)
676         value = self.get(name) + sep + value
677         self.write("append", name, value)
678
679     def run_env_script(self, module, script):
680         self.write("load", script, "", sign="")
681
682
683 #
684 #  Headers
685 #
686 bat_header="""\
687 @echo off
688
689 rem The following variables are used only in case of a sat package
690 set out_dir_Path=%~dp0
691 """
692
693 tcl_header="""\
694 #%Module -*- tcl -*-
695 #
696 # <module_name> module for use with 'environment-modules' package
697 #
698 """
699
700 bash_header="""\
701 #!/bin/bash
702 ##########################################################################
703 #
704 # This line is used only in case of a sat package
705 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
706
707 ###########################################################################
708 """
709
710 cfg_header="""\
711 [SALOME Configuration]
712 """
713
714 launcher_header2="""\
715 #! /usr/bin/env python
716
717 ################################################################
718 # WARNING: this file is automatically generated by SalomeTools #
719 # WARNING: and so could be overwritten at any time.            #
720 ################################################################
721
722 import os
723 import sys
724 import subprocess
725
726
727 # Add the pwdPath to able to run the launcher after unpacking a package
728 # Used only in case of a salomeTools package
729 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
730
731 # Preliminary work to initialize path to SALOME Python modules
732 def __initialize():
733
734   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]  # to get salomeContext
735   
736   # define folder to store omniorb config (initially in virtual application folder)
737   try:
738     from salomeContextUtils import setOmniOrbUserPath
739     setOmniOrbUserPath()
740   except Exception as e:
741     print(e)
742     sys.exit(1)
743 # End of preliminary work
744
745 # salome doc only works for virtual applications. Therefore we overwrite it with this function
746 def _showDoc(modules):
747     for module in modules:
748       modulePath = os.getenv(module+"_ROOT_DIR")
749       if modulePath != None:
750         baseDir = os.path.join(modulePath, "share", "doc", "salome")
751         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
752         if not os.path.isfile(docfile):
753           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
754         if not os.path.isfile(docfile):
755           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
756         if os.path.isfile(docfile):
757           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
758         else:
759           print ("Online documentation is not accessible for module:", module)
760       else:
761         print (module+"_ROOT_DIR not found!")
762
763 def main(args):
764   # Identify application path then locate configuration files
765   __initialize()
766
767   if args == ['--help']:
768     from salomeContext import usage
769     usage()
770     sys.exit(0)
771
772
773   # Create a SalomeContext which parses configFileNames to initialize environment
774   try:
775     from salomeContext import SalomeContext, SalomeContextException
776     context = SalomeContext(None)
777     
778     # Here set specific variables, if needed
779     # context.addToPath('mypath')
780     # context.addToLdLibraryPath('myldlibrarypath')
781     # context.addToPythonPath('mypythonpath')
782     # context.setVariable('myvarname', 'value')
783
784     # Logger level error
785     context.getLogger().setLevel(40)
786 """
787
788 launcher_header3="""\
789 #! /usr/bin/env python3
790
791 ################################################################
792 # WARNING: this file is automatically generated by SalomeTools #
793 # WARNING: and so could be overwritten at any time.            #
794 ################################################################
795
796 import os
797 import sys
798 import subprocess
799
800
801 # Add the pwdPath to able to run the launcher after unpacking a package
802 # Used only in case of a salomeTools package
803 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
804
805 # Preliminary work to initialize path to SALOME Python modules
806 def __initialize():
807
808   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
809   
810   # define folder to store omniorb config (initially in virtual application folder)
811   try:
812     from salomeContextUtils import setOmniOrbUserPath
813     setOmniOrbUserPath()
814   except Exception as e:
815     print(e)
816     sys.exit(1)
817 # End of preliminary work
818
819 # salome doc only works for virtual applications. Therefore we overwrite it with this function
820 def _showDoc(modules):
821     for module in modules:
822       modulePath = os.getenv(module+"_ROOT_DIR")
823       if modulePath != None:
824         baseDir = os.path.join(modulePath, "share", "doc", "salome")
825         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
826         if not os.path.isfile(docfile):
827           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
828         if not os.path.isfile(docfile):
829           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
830         if os.path.isfile(docfile):
831           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
832         else:
833           print("Online documentation is not accessible for module:", module)
834       else:
835         print(module+"_ROOT_DIR not found!")
836
837 def main(args):
838   # Identify application path then locate configuration files
839   __initialize()
840
841   if args == ['--help']:
842     from salomeContext import usage
843     usage()
844     sys.exit(0)
845
846   #from salomeContextUtils import getConfigFileNames
847   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
848   #if len(unexisting) > 0:
849   #  print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
850   #  sys.exit(1)
851
852   # Create a SalomeContext which parses configFileNames to initialize environment
853   try:
854     from salomeContext import SalomeContext, SalomeContextException
855     context = SalomeContext(None)
856     
857     # Here set specific variables, if needed
858     # context.addToPath('mypath')
859     # context.addToLdLibraryPath('myldlibrarypath')
860     # context.addToPythonPath('mypythonpath')
861     # context.setVariable('myvarname', 'value')
862
863     # Logger level error
864     context.getLogger().setLevel(40)
865 """
866
867 launcher_tail_py2="""\
868     if len(args) >1 and args[0]=='doc':
869         _showDoc(args[1:])
870         return
871
872     # Start SALOME, parsing command line arguments
873     out, err, status = context.runSalome(args)
874     sys.exit(status)
875
876   except SalomeContextException, e:
877     import logging
878     logging.getLogger("salome").error(e)
879     sys.exit(1)
880 #
881
882 if __name__ == "__main__":
883   args = sys.argv[1:]
884   main(args)
885 #
886 """
887
888 launcher_tail_py3="""\
889     if len(args) >1 and args[0]=='doc':
890         _showDoc(args[1:])
891         return
892
893     # Start SALOME, parsing command line arguments
894     out, err, status = context.runSalome(args)
895     sys.exit(status)
896
897   except SalomeContextException as e:
898     import logging
899     logging.getLogger("salome").error(e)
900     sys.exit(1)
901 #
902
903 if __name__ == "__main__":
904   args = sys.argv[1:]
905   main(args)
906 #
907 """
908     
909