3 # Copyright (C) 2010-2013 CEA/DEN
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.
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.
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
21 import src.debug as DBG
22 import src.architecture
23 import src.environment
28 rem The following variables are used only in case of a sat package
29 set out_dir_Path=%~dp0
35 ##########################################################################
38 # cleanup a path (first parameter) from duplicated entries;
39 # second parameter is the separator
41 out_var=`echo $1 | awk -v sep=$2 '{ \\
42 na = split($1,a,sep); \\
44 for(i=0;i<=na;i++) { \\
61 }' | sed -e 's|\\(.*\\)$1|\\1|g' -e 's|^[:;]||' -e 's|[:;]$||'`
68 out_var=`cleandup $xenv $2`
72 # This line is used only in case of a sat package
73 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
75 ###########################################################################
79 [SALOME Configuration]
83 # a generated SALOME Configuration file using python syntax
86 def get_file_environ(output, shell, environ=None):
87 """Instantiate correct FileEnvironment sub-class.
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.
94 return BashFileEnviron(output, src.environment.Environ({}))
96 return BatFileEnviron(output, src.environment.Environ({}))
97 if shell == "cfgForPy":
98 return LauncherFileEnviron(output, environ)
100 return ContextFileEnviron(output, src.environment.Environ({}))
101 raise Exception("FileEnviron: Unknown shell = %s" % shell)
103 class FileEnviron(object):
105 Base class for shell environment
107 def __init__(self, output, environ=None):
111 :param output file: the output file stream.
112 :param environ dict: a potential additional environment.
114 self._do_init(output, environ)
118 easy non exhaustive quick resume for debug print"""
120 "output" : self.output,
121 "environ" : self.environ,
123 return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
126 def _do_init(self, output, environ=None):
130 :param output file: the output file stream.
131 :param environ dict: a potential additional environment.
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
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
143 def add_line(self, number):
145 Add some empty lines in the shell file
147 :param number int: the number of lines to add
149 self.output.write("\n" * number)
151 def add_comment(self, comment):
153 Add a comment in the shell file
155 :param comment str: the comment to add
157 self.output.write("# %s\n" % comment)
159 def add_echo(self, text):
161 Add a "echo" in the shell file
163 :param text str: the text to echo
165 self.output.write('echo %s"\n' % text)
167 def add_warning(self, warning):
169 Add a warning "echo" in the shell file
171 :param warning str: the text to echo
173 self.output.write('echo "WARNING %s"\n' % warning)
175 def append_value(self, key, value, sep=os.pathsep):
177 append value to key using sep,
178 if value contains ":" or ";" then raise error
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
184 # check that value so no contain the system separator
186 if separator in value:
187 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
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)
196 self.environ.append_value(key, value,sep)
197 self.set(key, self.get(key) + sep + value)
199 def append(self, key, value, sep=os.pathsep):
201 Same as append_value but the value argument can be a list
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
207 if isinstance(value, list):
209 self.append_value(key, v, sep)
211 self.append_value(key, value, sep)
213 def prepend_value(self, key, value, sep=os.pathsep):
215 prepend value to key using sep,
216 if value contains ":" or ";" then raise error
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
222 # check that value so no contain the system separator
224 if separator in value:
225 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
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:
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))
238 def prepend(self, key, value, sep=os.pathsep):
240 Same as prepend_value but the value argument can be a list
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
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)
250 self.prepend_value(key, value, sep)
252 def is_defined(self, key):
254 Check if the key exists in the environment
256 :param key str: the environment variable to check
258 return self.environ.is_defined(key)
260 def set(self, key, value):
262 Set the environment variable 'key' to value 'value'
264 :param key str: the environment variable to set
265 :param value str: the value
267 raise NotImplementedError("set is not implement for this shell!")
271 Get the value of the environment variable "key"
273 :param key str: the environment variable
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
282 return self.environ.get_value(key)
285 """Add a final instruction in the out file (in case of file generation)
287 :param required bool: Do nothing if required is False
289 raise NotImplementedError("finish is not implement "
292 class BashFileEnviron(FileEnviron):
294 Class for bash shell.
296 def __init__(self, output, environ=None):
299 :param output file: the output file stream.
300 :param environ dict: a potential additional environment.
302 self._do_init(output, environ)
303 self.output.write(bash_header)
305 def set(self, key, value):
306 """Set the environment variable "key" to value "value"
308 :param key str: the environment variable to set
309 :param value str: the value
311 self.output.write('export %s="%s"\n' % (key, value))
312 self.environ.set(key, value)
316 class BatFileEnviron(FileEnviron):
318 for Windows batch shell.
320 def __init__(self, output, environ=None):
323 :param output file: the output file stream.
324 :param environ dict: a potential additional environment.
326 self._do_init(output, environ)
327 self.output.write(bat_header)
329 def add_comment(self, comment):
330 """Add a comment in the shell file
332 :param comment str: the comment to add
334 self.output.write("rem %s\n" % comment)
337 """Get the value of the environment variable "key"
339 :param key str: the environment variable
341 return '%%%s%%' % key
343 def set(self, key, value):
344 """Set the environment variable "key" to value "value"
346 :param key str: the environment variable to set
347 :param value str: the value
349 self.output.write('set %s=%s\n' % (key, value))
350 self.environ.set(key, value)
352 def finish(self, required=True):
354 Add a final instruction in the out file (in case of file generation)
355 In the particular windows case, do nothing
357 :param required bool: Do nothing if required is False
361 class ContextFileEnviron(FileEnviron):
362 """Class for a salome context configuration file.
364 def __init__(self, output, environ=None):
367 :param output file: the output file stream.
368 :param environ dict: a potential additional environment.
370 self._do_init(output, environ)
371 self.output.write(cfg_header)
373 def set(self, key, value):
374 """Set the environment variable "key" to value "value"
376 :param key str: the environment variable to set
377 :param value str: the value
379 self.output.write('%s="%s"\n' % (key, value))
380 self.environ.set(key, value)
383 """Get the value of the environment variable "key"
385 :param key str: the environment variable
387 return '%({0})s'.format(key)
389 def add_echo(self, text):
392 :param text str: the comment to add
394 self.add_comment(text)
396 def add_warning(self, warning):
399 :param text str: the warning to add
401 self.add_comment("WARNING %s" % warning)
403 def prepend_value(self, key, value, sep=os.pathsep):
404 """prepend value to key using sep
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
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
418 self.environ.append_value(key, value,sep)
419 self.output.write('ADD_TO_%s: %s\n' % (key, value))
421 def append_value(self, key, value, sep=os.pathsep):
422 """append value to key using sep
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
428 self.prepend_value(key, value)
430 def finish(self, required=True):
431 """Add a final instruction in the out file (in case of file generation)
433 :param required bool: Do nothing if required is False
437 def special_path_separator(name):
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.
444 :param name str: The name of the variable to find the separator
446 special_blanks_keys=["TCLLIBPATH", "TKLIBPATH"]
447 special_semicolon_keys=["PV_PLUGIN_PATH"]
449 if name in special_blanks_keys: res=" "
450 if name in special_semicolon_keys: res=";"
453 class LauncherFileEnviron:
455 Class to generate a launcher file script
456 (in python syntax) SalomeContext API
458 def __init__(self, output, environ=None):
461 :param output file: the output file stream.
462 :param environ dict: a potential additional environment.
465 if environ is not None:
466 self.environ = environ
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"]=""
481 # four whitespaces for first indentation in a python script
483 self.prefix="context."
484 self.setVarEnv="setVariable"
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"}
492 def change_to_launcher(self, value):
496 def add_line(self, number):
497 """Add some empty lines in the launcher file
499 :param number int: the number of lines to add
501 self.output.write("\n" * number)
503 def add_echo(self, text):
506 :param text str: the comment to add
508 self.output.write('# %s"\n' % text)
510 def add_warning(self, warning):
513 :param text str: the warning to add
515 self.output.write('# "WARNING %s"\n' % warning)
517 def append_value(self, key, value, sep=":"):
518 """append value to key using sep,
519 if value contains ":" or ";" then raise error
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
525 # check that value so no contain the system separator
527 if separator in value:
528 raise Exception("LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
530 if self.is_defined(key) :
535 def append(self, key, value, sep=":"):
536 """Same as append_value but the value argument can be a list
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
542 if isinstance(value, list):
544 self.append_value(key, v, sep)
546 self.append_value(key, value, sep)
548 def prepend_value(self, key, value, sep=":"):
549 """prepend value to key using sep,
550 if value contains ":" or ";" then raise error
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
556 # check that value so no contain the system separator
558 if separator in value:
559 raise Exception("LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
561 if self.is_defined(key) :
566 def prepend(self, key, value, sep=":"):
567 """Same as prepend_value but the value argument can be a list
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
573 if isinstance(value, list):
575 self.prepend_value(key, v, sep)
577 self.prepend_value(key, value, sep)
579 def is_defined(self, key):
580 """Check if the key exists in the environment
582 :param key str: the environment variable to check
584 return key in self.environ.keys()
587 """Get the value of the environment variable "key"
589 :param key str: the environment variable
593 def set(self, key, value):
594 """Set the environment variable "key" to value "value"
596 :param key str: the environment variable to set
597 :param value str: the value
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
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
609 return self.environ[key]
611 def add(self, key, value):
612 """prepend value to key using sep
614 :param key str: the environment variable to prepend
615 :param value str: the value to prepend to key
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
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' %
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
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+
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+
649 '(r"%s", r"%s", overwrite=True)\n' %
651 self.change_to_launcher(
654 if "setting environ for" in comment:
655 self.output.write(self.indent+"#[%s]\n" %
656 comment.split("setting environ for ")[1])
659 self.output.write(self.indent+"# %s\n" % comment)
661 def finish(self, required=True):
663 Add a final instruction in the out file (in case of file generation)
664 In the particular launcher case, do nothing
666 :param required bool: Do nothing if required is False
670 class ScreenEnviron(FileEnviron):
671 def __init__(self, output, environ=None):
672 self._do_init(output, environ)
675 def add_line(self, number):
678 def add_comment(self, comment):
681 def add_echo(self, text):
684 def add_warning(self, warning):
687 def write(self, command, name, value, sign="="):
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))
694 def is_defined(self, name):
695 return name in self.defined
698 return "${%s}" % name
700 def set(self, name, value):
701 self.write("set", name, value)
702 self.defined[name] = value
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)
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)
716 def run_env_script(self, module, script):
717 self.write("load", script, "", sign="")
719 # The SALOME launcher template
721 #! /usr/bin/env python
723 ################################################################
724 # WARNING: this file is automatically generated by SalomeTools #
725 # WARNING: and so could be overwritten at any time. #
726 ################################################################
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__))
737 # Preliminary work to initialize path to SALOME Python modules
740 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
741 os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
743 # define folder to store omniorb config (initially in virtual application folder)
745 from salomeContextUtils import setOmniOrbUserPath
747 except Exception as e:
750 # End of preliminary work
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()
766 print "Online documentation is not accessible for module:", module
768 print module+"_ROOT_DIR not found!"
771 # Identify application path then locate configuration files
774 if args == ['--help']:
775 from salomeContext import usage
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)
785 # Create a SalomeContext which parses configFileNames to initialize environment
787 from salomeContext import SalomeContext, SalomeContextException
788 SalomeContext.addToSpecial=addToSpecial
789 context = SalomeContext(None)
791 # Here set specific variables, if needed
792 # context.addToPath('mypath')
793 # context.addToLdLibraryPath('myldlibrarypath')
794 # context.addToPythonPath('mypythonpath')
795 # context.setVariable('myvarname', 'value')
798 context.getLogger().setLevel(40)
800 # here your local standalone environment
802 if len(args) >1 and args[0]=='doc':
806 # Start SALOME, parsing command line arguments
807 out, err, status = context.runSalome(args)
810 except SalomeContextException, e:
812 logging.getLogger("salome").error(e)
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.
822 specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
823 specialSemicolonKeys=["PV_PLUGIN_PATH"]
825 if name in specialBlanksKeys: res=" "
826 if name in specialSemicolonKeys: res=";"
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)
836 os.environ[name] = value
838 os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
840 if __name__ == "__main__":
847 #! /usr/bin/env python3
849 ################################################################
850 # WARNING: this file is automatically generated by SalomeTools #
851 # WARNING: and so could be overwritten at any time. #
852 ################################################################
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__))
863 # Preliminary work to initialize path to SALOME Python modules
866 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
867 os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
869 # define folder to store omniorb config (initially in virtual application folder)
871 from salomeContextUtils import setOmniOrbUserPath
873 except Exception as e:
876 # End of preliminary work
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()
892 print("Online documentation is not accessible for module:", module)
894 print(module+"_ROOT_DIR not found!")
897 # Identify application path then locate configuration files
900 if args == ['--help']:
901 from salomeContext import usage
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))
911 # Create a SalomeContext which parses configFileNames to initialize environment
913 from salomeContext import SalomeContext, SalomeContextException
914 SalomeContext.addToSpecial=addToSpecial
915 context = SalomeContext(None)
917 # Here set specific variables, if needed
918 # context.addToPath('mypath')
919 # context.addToLdLibraryPath('myldlibrarypath')
920 # context.addToPythonPath('mypythonpath')
921 # context.setVariable('myvarname', 'value')
924 context.getLogger().setLevel(40)
926 # here your local standalone environment
928 if len(args) >1 and args[0]=='doc':
932 # Start SALOME, parsing command line arguments
933 out, err, status = context.runSalome(args)
936 except SalomeContextException as e:
938 logging.getLogger("salome").error(e)
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.
948 specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
949 specialSemicolonKeys=["PV_PLUGIN_PATH"]
951 if name in specialBlanksKeys: res=" "
952 if name in specialSemicolonKeys: res=";"
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)
962 os.environ[name] = value
964 os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
966 if __name__ == "__main__":