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