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