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