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