Salome HOME
utilisation d'environ pour éviter les duplications dans les chemins
[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 command_value(self, key, command):
285         """\
286         Get the value given by the system command "command" 
287         and put it in the environment variable key.
288         Has to be overwritten in the derived classes
289         This can be seen as a virtual method
290         
291         :param key str: the environment variable
292         :param command str: the command to execute
293         """
294         raise NotImplementedError("command_value is not implement "
295                                   "for this shell!")
296
297     def finish(self):
298         """Add a final instruction in the out file (in case of file generation)
299         
300         :param required bool: Do nothing if required is False
301         """
302         raise NotImplementedError("command_value is not implement "
303                                   "for this shell!")
304
305 class BashFileEnviron(FileEnviron):
306     """\
307     Class for bash shell.
308     """
309     def __init__(self, output, environ=None):
310         """Initialization
311         
312         :param output file: the output file stream.
313         :param environ dict: a potential additional environment.
314         """
315         self._do_init(output, environ)
316         self.output.write(bash_header)
317
318     def set(self, key, value):
319         """Set the environment variable "key" to value "value"
320         
321         :param key str: the environment variable to set
322         :param value str: the value
323         """
324         self.output.write('export %s="%s"\n' % (key, value))
325         self.environ.set(key, value)
326         
327
328     def command_value(self, key, command):
329         """\
330         Get the value given by the system command "command" 
331         and put it in the environment variable key.
332         Has to be overwritten in the derived classes
333         This can be seen as a virtual method
334         
335         :param key str: the environment variable
336         :param command str: the command to execute
337         """
338         self.output.write('export %s=$(%s)\n' % (key, command))
339
340         
341 class BatFileEnviron(FileEnviron):
342     """\
343     for Windows batch shell.
344     """
345     def __init__(self, output, environ=None):
346         """Initialization
347         
348         :param output file: the output file stream.
349         :param environ dict: a potential additional environment.
350         """
351         self._do_init(output, environ)
352         self.output.write(bat_header)
353
354     def add_comment(self, comment):
355         """Add a comment in the shell file
356         
357         :param comment str: the comment to add
358         """
359         self.output.write("rem %s\n" % comment)
360     
361     def get(self, key):
362         """Get the value of the environment variable "key"
363         
364         :param key str: the environment variable
365         """
366         return '%%%s%%' % key
367     
368     def set(self, key, value):
369         """Set the environment variable "key" to value "value"
370         
371         :param key str: the environment variable to set
372         :param value str: the value
373         """
374         self.output.write('set %s=%s\n' % (key, value))
375         self.environ.set(key, value)
376
377     def command_value(self, key, command):
378         """\
379         Get the value given by the system command "command" 
380         and put it in the environment variable key.
381         Has to be overwritten in the derived classes
382         This can be seen as a virtual method
383         
384         :param key str: the environment variable
385         :param command str: the command to execute
386         """
387         self.output.write('%s > tmp.txt\n' % (command))
388         self.output.write('set /p %s =< tmp.txt\n' % (key))
389
390     def finish(self, required=True):
391         """\
392         Add a final instruction in the out file (in case of file generation)
393         In the particular windows case, do nothing
394         
395         :param required bool: Do nothing if required is False
396         """
397         return
398
399 class ContextFileEnviron(FileEnviron):
400     """Class for a salome context configuration file.
401     """
402     def __init__(self, output, environ=None):
403         """Initialization
404         
405         :param output file: the output file stream.
406         :param environ dict: a potential additional environment.
407         """
408         self._do_init(output, environ)
409         self.output.write(cfg_header)
410
411     def set(self, key, value):
412         """Set the environment variable "key" to value "value"
413         
414         :param key str: the environment variable to set
415         :param value str: the value
416         """
417         self.output.write('%s="%s"\n' % (key, value))
418         self.environ.set(key, value)
419
420     def get(self, key):
421         """Get the value of the environment variable "key"
422         
423         :param key str: the environment variable
424         """
425         return '%({0})s'.format(key)
426
427     def command_value(self, key, command):
428         """\
429         Get the value given by the system command "command" 
430         and put it in the environment variable key.
431         Has to be overwritten in the derived classes
432         This can be seen as a virtual method
433         
434         :param key str: the environment variable
435         :param command str: the command to execute
436         """
437         raise NotImplementedError("command_value is not implement "
438                                   "for salome context files!")
439
440     def add_echo(self, text):
441         """Add a comment
442         
443         :param text str: the comment to add
444         """
445         self.add_comment(text)
446
447     def add_warning(self, warning):
448         """Add a warning
449         
450         :param text str: the warning to add
451         """
452         self.add_comment("WARNING %s"  % warning)
453
454     def prepend_value(self, key, value, sep=os.pathsep):
455         """prepend value to key using sep
456         
457         :param key str: the environment variable to prepend
458         :param value str: the value to prepend to key
459         :param sep str: the separator string
460         """
461         do_append=True
462         if self.environ.is_defined(key):
463             value_list = self.environ.get(key).split(sep)
464             #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
465             if value in value_list:
466                 do_append=False  # value is already in key path : we don't append it again
467             
468         if do_append:
469             self.environ.append_value(key, value,sep)
470             self.output.write('ADD_TO_%s: %s\n' % (key, value))
471
472     def append_value(self, key, value, sep=os.pathsep):
473         """append value to key using sep
474         
475         :param key str: the environment variable to append
476         :param value str: the value to append to key
477         :param sep str: the separator string
478         """
479         self.prepend_value(key, value)
480
481     def finish(self, required=True):
482         """Add a final instruction in the out file (in case of file generation)
483         
484         :param required bool: Do nothing if required is False
485         """
486         return
487
488 def special_path_separator(name):
489     """\
490     TCLLIBPATH, TKLIBPATH, PV_PLUGIN_PATH environments variables need
491     some exotic path separator.
492     This function gives the separator regarding the name of the variable
493     to append or prepend.
494        
495     :param name str: The name of the variable to find the separator
496     """
497     special_blanks_keys=["TCLLIBPATH", "TKLIBPATH"]
498     special_semicolon_keys=["PV_PLUGIN_PATH"]
499     res=os.pathsep
500     if name in special_blanks_keys: res=" "
501     if name in special_semicolon_keys: res=";"
502     return res
503
504 class LauncherFileEnviron:
505     """\
506     Class to generate a launcher file script 
507     (in python syntax) SalomeContext API
508     """
509     def __init__(self, output, environ=None):
510         """Initialization
511         
512         :param output file: the output file stream.
513         :param environ dict: a potential additional environment.
514         """
515         self.output = output
516         if environ is not None:
517             self.environ = environ
518         else:
519             self.environ = os.environ
520         # Initialize some variables
521         if not "PATH" in self.environ.keys():
522             self.environ["PATH"]=""
523         if not "LD_LIBRARY_PATH" in self.environ.keys():
524             self.environ["LD_LIBRARY_PATH"]=""
525         if not "PYTHONPATH" in self.environ.keys():
526             self.environ["PYTHONPATH"]=""
527         if not "TCLLIBPATH" in self.environ.keys():
528             self.environ["TCLLIBPATH"]=""
529         if not "TKLIBPATH" in self.environ.keys():
530             self.environ["TKLIBPATH"]=""
531
532         # four whitespaces for first indentation in a python script
533         self.indent="    "
534         self.prefix="context."
535         self.setVarEnv="setVariable"
536         
537         self.begin=self.indent+self.prefix
538         self.output.write(Launcher_header)
539         self.specialKeys={"PATH": "Path",
540                           "LD_LIBRARY_PATH": "LdLibraryPath",
541                           "PYTHONPATH": "PythonPath"}
542
543     def change_to_launcher(self, value):
544         res=value
545         return res
546
547     def add_line(self, number):
548         """Add some empty lines in the launcher file
549         
550         :param number int: the number of lines to add
551         """
552         self.output.write("\n" * number)
553
554     def add_echo(self, text):
555         """Add a comment
556         
557         :param text str: the comment to add
558         """
559         self.output.write('# %s"\n' % text)
560
561     def add_warning(self, warning):
562         """Add a warning
563         
564         :param text str: the warning to add
565         """
566         self.output.write('# "WARNING %s"\n' % warning)
567
568     def append_value(self, key, value, sep=":"):
569         """append value to key using sep,
570         if value contains ":" or ";" then raise error
571         
572         :param key str: the environment variable to append
573         :param value str: the value to append to key
574         :param sep str: the separator string
575         """
576         # check that value so no contain the system separator
577         separator=os.pathsep
578         if separator in value:
579             raise Exception("LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
580
581         if self.is_defined(key) :
582             self.add(key, value)
583         else :
584             self.set(key, value)
585
586     def append(self, key, value, sep=":"):
587         """Same as append_value but the value argument can be a list
588         
589         :param key str: the environment variable to append
590         :param value str or list: the value(s) to append to key
591         :param sep str: the separator string
592         """
593         if isinstance(value, list):
594             for v in value:
595                 self.append_value(key, v, sep)
596         else:
597             self.append_value(key, value, sep)
598
599     def prepend_value(self, key, value, sep=":"):
600         """prepend value to key using sep,
601         if value contains ":" or ";" then raise error
602         
603         :param key str: the environment variable to prepend
604         :param value str: the value to prepend to key
605         :param sep str: the separator string
606         """
607         # check that value so no contain the system separator
608         separator=os.pathsep
609         if separator in value:
610             raise Exception("LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
611
612         if self.is_defined(key) :
613             self.add(key, value)
614         else :
615             self.set(key, value)
616
617     def prepend(self, key, value, sep=":"):
618         """Same as prepend_value but the value argument can be a list
619         
620         :param key str: the environment variable to prepend
621         :param value str or list: the value(s) to prepend to key
622         :param sep str: the separator string
623         """
624         if isinstance(value, list):
625             for v in value:
626                 self.prepend_value(key, v, sep)
627         else:
628             self.prepend_value(key, value, sep)
629
630     def is_defined(self, key):
631         """Check if the key exists in the environment
632         
633         :param key str: the environment variable to check
634         """
635         return key in self.environ.keys()
636
637     def get(self, key):
638         """Get the value of the environment variable "key"
639         
640         :param key str: the environment variable
641         """
642         return '${%s}' % key
643
644     def set(self, key, value):
645         """Set the environment variable "key" to value "value"
646         
647         :param key str: the environment variable to set
648         :param value str: the value
649         """
650         self.output.write(self.begin+self.setVarEnv+
651                           '(r"%s", r"%s", overwrite=True)\n' % 
652                           (key, self.change_to_launcher(value)))
653         self.environ[key] = value
654     
655     def get_value(self, key):
656         """Get the real value of the environment variable "key", not ${key}
657         It can help env scripts
658         :param key str: the environment variable
659         """
660         return self.environ[key]
661
662     def add(self, key, value):
663         """prepend value to key using sep
664         
665         :param key str: the environment variable to prepend
666         :param value str: the value to prepend to key
667         """     
668         if key in self.specialKeys.keys():
669             self.output.write(self.begin+'addTo%s(r"%s")\n' % 
670                               (self.specialKeys[key],
671                                self.change_to_launcher(value)))
672             self.environ[key]+=":"+value
673             return
674         sep=special_path_separator(key)
675         self.output.write(self.indent+
676                           '#temporary solution!!! have to be defined in API a '
677                           '?dangerous? addToSpecial(r"%s", r"%s")\n' % 
678                           (key, value))
679         #pathsep not precised because do not know future os launch?
680         self.output.write(self.begin+'addToSpecial(r"%s", r"%s")\n' 
681                           % (key, self.change_to_launcher(value)))
682         self.environ[key]+=sep+value #here yes we know os for current execution
683
684     def command_value(self, key, command):
685         """\
686         Get the value given by the system command "command" 
687         and put it in the environment variable key.
688         
689         :param key str: the environment variable
690         :param command str: the command to execute
691         """
692         self.output.write(self.indent+'#`%s`\n' % command)
693
694         import shlex, subprocess
695         args = shlex.split(command)
696         res=subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
697         out, __ = res.communicate()
698         self.output.write(self.begin+
699                           self.setVarEnv+
700                           '(r"%s", r"%s", overwrite=True)\n' % (key, out))
701
702     def add_comment(self, comment):
703         # Special comment in case of the distène licence
704         if comment=="DISTENE license":
705             self.output.write(self.indent+
706                               "#"+
707                               self.prefix+
708                               self.setVarEnv+
709                               '(r"%s", r"%s", overwrite=True)\n' % 
710                               ('DISTENE_LICENSE_FILE', 
711                                self.change_to_launcher(
712                                             'Use global envvar: DLIM8VAR')))
713             self.output.write(self.indent+
714                               "#"+
715                               self.prefix+
716                               self.setVarEnv+
717                               '(r"%s", r"%s", overwrite=True)\n' % 
718                               ('DLIM8VAR', 
719                                self.change_to_launcher(
720                                                 '<your licence>')))
721             return
722         if "setting environ for" in comment:
723             self.output.write(self.indent+"#[%s]\n" % 
724                               comment.split("setting environ for ")[1])
725             return
726
727         self.output.write(self.indent+"# %s\n" % comment)
728
729     def finish(self, required=True):
730         """\
731         Add a final instruction in the out file (in case of file generation)
732         In the particular launcher case, do nothing
733         
734         :param required bool: Do nothing if required is False
735         """
736         return
737
738 class ScreenEnviron(FileEnviron):
739     def __init__(self, output, environ=None):
740         self._do_init(output, environ)
741         self.defined = {}
742
743     def add_line(self, number):
744         pass
745
746     def add_comment(self, comment):
747         pass
748
749     def add_echo(self, text):
750         pass
751
752     def add_warning(self, warning):
753         pass
754
755     def write(self, command, name, value, sign="="):
756         import src
757         self.output.write("  %s%s %s %s %s\n" % \
758             (src.printcolors.printcLabel(command),
759              " " * (12 - len(command)),
760              src.printcolors.printcInfo(name), sign, value))
761
762     def is_defined(self, name):
763         return name in self.defined
764
765     def get(self, name):
766         return "${%s}" % name
767
768     def set(self, name, value):
769         self.write("set", name, value)
770         self.defined[name] = value
771
772     def prepend(self, name, value, sep=":"):
773         if isinstance(value, list):
774             value = sep.join(value)
775         value = value + sep + self.get(name)
776         self.write("prepend", name, value)
777
778     def append(self, name, value, sep=":"):
779         if isinstance(value, list):
780             value = sep.join(value)
781         value = self.get(name) + sep + value
782         self.write("append", name, value)
783
784     def command_value(self, key, command):
785         pass
786
787     def run_env_script(self, module, script):
788         self.write("load", script, "", sign="")
789
790 # The SALOME launcher template 
791 withProfile =  """\
792 #! /usr/bin/env python
793
794 ################################################################
795 # WARNING: this file is automatically generated by SalomeTools #
796 # WARNING: and so could be overwritten at any time.            #
797 ################################################################
798
799 import os
800 import sys
801 import subprocess
802
803
804 # Add the pwdPath to able to run the launcher after unpacking a package
805 # Used only in case of a salomeTools package
806 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
807
808 # Preliminary work to initialize path to SALOME Python modules
809 def __initialize():
810
811   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
812   os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
813   
814   # define folder to store omniorb config (initially in virtual application folder)
815   try:
816     from salomeContextUtils import setOmniOrbUserPath
817     setOmniOrbUserPath()
818   except Exception as e:
819     print(e)
820     sys.exit(1)
821 # End of preliminary work
822
823 # salome doc only works for virtual applications. Therefore we overwrite it with this function
824 def _showDoc(modules):
825     for module in modules:
826       modulePath = os.getenv(module+"_ROOT_DIR")
827       if modulePath != None:
828         baseDir = os.path.join(modulePath, "share", "doc", "salome")
829         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
830         if not os.path.isfile(docfile):
831           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
832         if not os.path.isfile(docfile):
833           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
834         if os.path.isfile(docfile):
835           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
836         else:
837           print "Online documentation is not accessible for module:", module
838       else:
839         print module+"_ROOT_DIR not found!"
840
841 def main(args):
842   # Identify application path then locate configuration files
843   __initialize()
844
845   if args == ['--help']:
846     from salomeContext import usage
847     usage()
848     sys.exit(0)
849
850   #from salomeContextUtils import getConfigFileNames
851   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
852   #if len(unexisting) > 0:
853   #  print "ERROR: unexisting configuration file(s): " + ', '.join(unexisting)
854   #  sys.exit(1)
855
856   # Create a SalomeContext which parses configFileNames to initialize environment
857   try:
858     from salomeContext import SalomeContext, SalomeContextException
859     SalomeContext.addToSpecial=addToSpecial
860     context = SalomeContext(None)
861     
862     # Here set specific variables, if needed
863     # context.addToPath('mypath')
864     # context.addToLdLibraryPath('myldlibrarypath')
865     # context.addToPythonPath('mypythonpath')
866     # context.setVariable('myvarname', 'value')
867
868     # Logger level error
869     context.getLogger().setLevel(40)
870
871     # here your local standalone environment
872
873     if len(args) >1 and args[0]=='doc':
874         _showDoc(args[1:])
875         return
876
877     # Start SALOME, parsing command line arguments
878     out, err, status = context.runSalome(args)
879     sys.exit(status)
880
881   except SalomeContextException, e:
882     import logging
883     logging.getLogger("salome").error(e)
884     sys.exit(1)
885 #
886 def addToSpecial(self, name, value, pathSep=None):
887   # add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc...
888   # http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
889   # TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
890   if value == '':
891     return
892   
893   specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
894   specialSemicolonKeys=["PV_PLUGIN_PATH"]
895   res=os.pathsep
896   if name in specialBlanksKeys: res=" "
897   if name in specialSemicolonKeys: res=";"
898   
899   if pathSep==None:
900     sep=res
901   else:
902     sep=pathSep
903   value = os.path.expandvars(value) # expand environment variables
904   self.getLogger().debug("Add to %s: %s", name, value)
905   env = os.getenv(name, None)
906   if env is None:
907     os.environ[name] = value
908   else:
909     os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
910
911 if __name__ == "__main__":
912   args = sys.argv[1:]
913   main(args)
914 #
915 """
916     
917 withProfile3 =  """\
918 #! /usr/bin/env python3
919
920 ################################################################
921 # WARNING: this file is automatically generated by SalomeTools #
922 # WARNING: and so could be overwritten at any time.            #
923 ################################################################
924
925 import os
926 import sys
927 import subprocess
928
929
930 # Add the pwdPath to able to run the launcher after unpacking a package
931 # Used only in case of a salomeTools package
932 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
933
934 # Preliminary work to initialize path to SALOME Python modules
935 def __initialize():
936
937   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
938   os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
939   
940   # define folder to store omniorb config (initially in virtual application folder)
941   try:
942     from salomeContextUtils import setOmniOrbUserPath
943     setOmniOrbUserPath()
944   except Exception as e:
945     print(e)
946     sys.exit(1)
947 # End of preliminary work
948
949 # salome doc only works for virtual applications. Therefore we overwrite it with this function
950 def _showDoc(modules):
951     for module in modules:
952       modulePath = os.getenv(module+"_ROOT_DIR")
953       if modulePath != None:
954         baseDir = os.path.join(modulePath, "share", "doc", "salome")
955         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
956         if not os.path.isfile(docfile):
957           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
958         if not os.path.isfile(docfile):
959           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
960         if os.path.isfile(docfile):
961           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
962         else:
963           print("Online documentation is not accessible for module:", module)
964       else:
965         print(module+"_ROOT_DIR not found!")
966
967 def main(args):
968   # Identify application path then locate configuration files
969   __initialize()
970
971   if args == ['--help']:
972     from salomeContext import usage
973     usage()
974     sys.exit(0)
975
976   #from salomeContextUtils import getConfigFileNames
977   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
978   #if len(unexisting) > 0:
979   #  print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
980   #  sys.exit(1)
981
982   # Create a SalomeContext which parses configFileNames to initialize environment
983   try:
984     from salomeContext import SalomeContext, SalomeContextException
985     SalomeContext.addToSpecial=addToSpecial
986     context = SalomeContext(None)
987     
988     # Here set specific variables, if needed
989     # context.addToPath('mypath')
990     # context.addToLdLibraryPath('myldlibrarypath')
991     # context.addToPythonPath('mypythonpath')
992     # context.setVariable('myvarname', 'value')
993
994     # Logger level error
995     context.getLogger().setLevel(40)
996
997     # here your local standalone environment
998
999     if len(args) >1 and args[0]=='doc':
1000         _showDoc(args[1:])
1001         return
1002
1003     # Start SALOME, parsing command line arguments
1004     out, err, status = context.runSalome(args)
1005     sys.exit(status)
1006
1007   except SalomeContextException as e:
1008     import logging
1009     logging.getLogger("salome").error(e)
1010     sys.exit(1)
1011 #
1012 def addToSpecial(self, name, value, pathSep=None):
1013   # add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc...
1014   # http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
1015   # TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
1016   if value == '':
1017     return
1018   
1019   specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
1020   specialSemicolonKeys=["PV_PLUGIN_PATH"]
1021   res=os.pathsep
1022   if name in specialBlanksKeys: res=" "
1023   if name in specialSemicolonKeys: res=";"
1024   
1025   if pathSep==None:
1026     sep=res
1027   else:
1028     sep=pathSep
1029   value = os.path.expandvars(value) # expand environment variables
1030   self.getLogger().debug("Add to %s: %s", name, value)
1031   env = os.getenv(name, None)
1032   if env is None:
1033     os.environ[name] = value
1034   else:
1035     os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
1036
1037 if __name__ == "__main__":
1038   args = sys.argv[1:]
1039   main(args)
1040 #
1041 """
1042