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 ##########################################################################
37 # This line is used only in case of a sat package
38 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
40 ###########################################################################
44 [SALOME Configuration]
48 # a generated SALOME Configuration file using python syntax
51 def get_file_environ(output, shell, environ=None):
52 """Instantiate correct FileEnvironment sub-class.
54 :param output file: the output file stream.
55 :param shell str: the type of shell syntax to use.
56 :param environ dict: a potential additional environment.
59 return BashFileEnviron(output, src.environment.Environ({}))
61 return BatFileEnviron(output, src.environment.Environ({}))
62 if shell == "cfgForPy":
63 return LauncherFileEnviron(output, src.environment.Environ({}))
65 return ContextFileEnviron(output, src.environment.Environ({}))
66 raise Exception("FileEnviron: Unknown shell = %s" % shell)
68 class FileEnviron(object):
70 Base class for shell environment
72 def __init__(self, output, environ=None):
76 :param output file: the output file stream.
77 :param environ dict: SalomeEnviron.
79 self._do_init(output, environ)
83 easy non exhaustive quick resume for debug print"""
85 "output" : self.output,
86 "environ" : self.environ,
88 return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
91 def _do_init(self, output, environ=None):
95 :param output file: the output file stream.
96 :param environ dict: a potential additional environment.
99 self.init_path=True # by default we initialise all paths, except PATH
100 if environ is not None:
101 self.environ = environ
103 self.environ = src.environment.Environ({})
105 def add_line(self, number):
107 Add some empty lines in the shell file
109 :param number int: the number of lines to add
111 self.output.write("\n" * number)
113 def add_comment(self, comment):
115 Add a comment in the shell file
117 :param comment str: the comment to add
119 self.output.write("# %s\n" % comment)
121 def add_echo(self, text):
123 Add a "echo" in the shell file
125 :param text str: the text to echo
127 self.output.write('echo %s"\n' % text)
129 def add_warning(self, warning):
131 Add a warning "echo" in the shell file
133 :param warning str: the text to echo
135 self.output.write('echo "WARNING %s"\n' % warning)
137 def append_value(self, key, value, sep=os.pathsep):
139 append value to key using sep,
140 if value contains ":" or ";" then raise error
142 :param key str: the environment variable to append
143 :param value str: the value to append to key
144 :param sep str: the separator string
146 # check that value so no contain the system separator
148 if separator in value:
149 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
151 if self.environ.is_defined(key):
152 value_list = self.environ.get(key).split(sep)
153 if self.environ._expandvars(value) in value_list:
154 do_append=False # value is already in key path : we don't append it again
155 #print "\nCNC append_value value is already set!! key=%s, val=%s value_list=%s\n" % (key,self.environ._expandvars(value), value_list)
158 self.environ.append_value(key, value,sep)
159 self.set(key, self.get(key) + sep + value)
161 def append(self, key, value, sep=os.pathsep):
163 Same as append_value but the value argument can be a list
165 :param key str: the environment variable to append
166 :param value str or list: the value(s) to append to key
167 :param sep str: the separator string
169 if isinstance(value, list):
171 self.append_value(key, v, sep)
173 self.append_value(key, value, sep)
175 def prepend_value(self, key, value, sep=os.pathsep):
177 prepend value to key using sep,
178 if value contains ":" or ";" then raise error
180 :param key str: the environment variable to prepend
181 :param value str: the value to prepend 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))
190 if self.environ.is_defined(key):
191 value_list = self.environ.get(key).split(sep)
192 exp_val=self.environ._expandvars(value)
193 if exp_val in value_list:
195 #print "\nCNC prepend_value value is already set!! key=%s, val=%s value_list=%s\n" % (key,exp_val, value_list)
196 if not do_not_prepend:
197 self.environ.prepend_value(key, value,sep)
198 self.set(key, value + sep + self.get(key))
200 def prepend(self, key, value, sep=os.pathsep):
202 Same as prepend_value but the value argument can be a list
204 :param key str: the environment variable to prepend
205 :param value str or list: the value(s) to prepend to key
206 :param sep str: the separator string
208 if isinstance(value, list):
209 for v in reversed(value): # prepend list, first item at last to stay first
210 self.prepend_value(key, v, sep)
212 self.prepend_value(key, value, sep)
214 def is_defined(self, key):
216 Check if the key exists in the environment
218 :param key str: the environment variable to check
220 return self.environ.is_defined(key)
222 def set(self, key, value):
224 Set the environment variable 'key' to value 'value'
226 :param key str: the environment variable to set
227 :param value str: the value
229 raise NotImplementedError("set is not implement for this shell!")
233 Get the value of the environment variable "key"
235 :param key str: the environment variable
239 def get_value(self, key):
240 """Get the real value of the environment variable "key"
241 It can help env scripts
242 :param key str: the environment variable
244 return self.environ.get_value(key)
246 def finish(self, required):
247 """Add a final instruction in the out file (in case of file generation)
249 :param required bool: Do nothing if required is False
253 def set_no_init_path(self):
254 """Set the no initialisation mode for all paths.
255 By default only PATH is not reinitialised. All others paths are
256 (LD_LIBRARY_PATH, PYTHONPATH, ...)
257 After the call to these function ALL PATHS ARE NOT REINITIALISED.
258 There initial value is inherited from the environment
262 def value_filter(self, value):
264 # on windows platform, replace / by \
265 if src.architecture.is_windows():
266 res = value.replace("/","\\")
270 class BashFileEnviron(FileEnviron):
272 Class for bash shell.
274 def __init__(self, output, environ=None):
277 :param output file: the output file stream.
278 :param environ dict: a potential additional environment.
280 self._do_init(output, environ)
281 self.output.write(bash_header)
283 def set(self, key, value):
284 """Set the environment variable "key" to value "value"
286 :param key str: the environment variable to set
287 :param value str: the value
289 self.output.write('export %s="%s"\n' % (key, value))
290 self.environ.set(key, value)
294 class BatFileEnviron(FileEnviron):
296 for Windows batch shell.
298 def __init__(self, output, environ=None):
301 :param output file: the output file stream.
302 :param environ dict: a potential additional environment.
304 self._do_init(output, environ)
305 self.output.write(bat_header)
307 def add_comment(self, comment):
308 """Add a comment in the shell file
310 :param comment str: the comment to add
312 self.output.write("rem %s\n" % comment)
315 """Get the value of the environment variable "key"
317 :param key str: the environment variable
319 return '%%%s%%' % key
321 def set(self, key, value):
322 """Set the environment variable "key" to value "value"
324 :param key str: the environment variable to set
325 :param value str: the value
327 self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
328 self.environ.set(key, value)
330 def finish(self, required=True):
332 Add a final instruction in the out file (in case of file generation)
333 In the particular windows case, do nothing
335 :param required bool: Do nothing if required is False
339 class ContextFileEnviron(FileEnviron):
340 """Class for a salome context configuration file.
342 def __init__(self, output, environ=None):
345 :param output file: the output file stream.
346 :param environ dict: a potential additional environment.
348 self._do_init(output, environ)
349 self.output.write(cfg_header)
351 def set(self, key, value):
352 """Set the environment variable "key" to value "value"
354 :param key str: the environment variable to set
355 :param value str: the value
357 self.output.write('%s="%s"\n' % (key, value))
358 self.environ.set(key, value)
361 """Get the value of the environment variable "key"
363 :param key str: the environment variable
365 return '%({0})s'.format(key)
367 def add_echo(self, text):
370 :param text str: the comment to add
372 self.add_comment(text)
374 def add_warning(self, warning):
377 :param text str: the warning to add
379 self.add_comment("WARNING %s" % warning)
381 def prepend_value(self, key, value, sep=os.pathsep):
382 """prepend value to key using sep
384 :param key str: the environment variable to prepend
385 :param value str: the value to prepend to key
386 :param sep str: the separator string
389 if self.environ.is_defined(key):
390 value_list = self.environ.get(key).split(sep)
391 #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
392 if value in value_list:
393 do_append=False # value is already in key path : we don't append it again
396 self.environ.append_value(key, value,sep)
397 self.output.write('ADD_TO_%s: %s\n' % (key, value))
399 def append_value(self, key, value, sep=os.pathsep):
400 """append value to key using sep
402 :param key str: the environment variable to append
403 :param value str: the value to append to key
404 :param sep str: the separator string
406 self.prepend_value(key, value)
408 def finish(self, required=True):
409 """Add a final instruction in the out file (in case of file generation)
411 :param required bool: Do nothing if required is False
416 class LauncherFileEnviron(FileEnviron):
418 Class to generate a launcher file script
419 (in python syntax) SalomeContext API
421 def __init__(self, output, environ=None):
424 :param output file: the output file stream.
425 :param environ dict: a potential additional environment.
427 self._do_init(output, environ)
429 # four whitespaces for first indentation in a python script
431 self.prefix="context."
432 self.setVarEnv="setVariable"
434 self.begin=self.indent+self.prefix
435 self.output.write(Launcher_header)
437 # for these path, we use specialired functions in salomeContext api
438 self.specialKeys={"PATH": "Path",
439 "LD_LIBRARY_PATH": "LdLibraryPath",
440 "PYTHONPATH": "PythonPath"}
442 # we do not want to reinitialise PATH.
443 # for that we make sure PATH is in self.environ
444 # and therefore we will not use setVariable for PATH
445 if not self.environ.is_defined("PATH"):
446 self.environ.set("PATH","")
449 def add_echo(self, text):
452 :param text str: the comment to add
454 self.output.write('# %s"\n' % text)
456 def add_warning(self, warning):
459 :param text str: the warning to add
461 self.output.write('# "WARNING %s"\n' % warning)
463 def append_value(self, key, value, sep=":"):
464 """append value to key using sep,
465 if value contains ":" or ";" then raise error
467 :param key str: the environment variable to append
468 :param value str: the value to append to key
469 :param sep str: the separator string
471 # append is not defined in context api
472 self.prepend_value(key, value)
474 def append(self, key, value, sep=":"):
475 """Same as append_value but the value argument can be a list
477 :param key str: the environment variable to append
478 :param value str or list: the value(s) to append to key
479 :param sep str: the separator string
481 if isinstance(value, list):
483 self.append_value(key, v, sep)
485 self.append_value(key, value, sep)
487 def prepend_value(self, key, value, sep=os.pathsep):
488 """prepend value to key using sep,
489 if value contains ":" or ";" then raise error
491 :param key str: the environment variable to prepend
492 :param value str: the value to prepend to key
493 :param sep str: the separator string
495 # check that value so no contain the system separator
497 msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
498 if separator in value:
499 raise Exception(msg % (key, value, separator))
501 if (self.init_path and (not self.environ.is_defined(key))):
502 # reinitialisation mode set to true (the default)
503 # for the first occurrence of key, we set it.
504 # therefore key will not be inherited from environment
507 # in all other cases we use append (except if value is already the key
509 if self.environ.is_defined(key):
510 value_list = self.environ.get(key).split(sep)
511 # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
512 if value in value_list:
513 do_append=False # value is already in key path : we don't append it again
516 self.environ.append_value(key, value,sep) # register value in self.environ
517 if key in self.specialKeys.keys():
518 #for these special keys we use the specific salomeContext function
519 self.output.write(self.begin+'addTo%s(r"%s")\n' %
520 (self.specialKeys[key], self.value_filter(value)))
522 # else we use the general salomeContext addToVariable function
523 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n'
524 % (key, self.value_filter(value), sep))
527 def prepend(self, key, value, sep=":"):
528 """Same as prepend_value but the value argument can be a list
530 :param key str: the environment variable to prepend
531 :param value str or list: the value(s) to prepend to key
532 :param sep str: the separator string
534 if isinstance(value, list):
536 self.prepend_value(key, v, sep)
538 self.prepend_value(key, value, sep)
541 def set(self, key, value):
542 """Set the environment variable "key" to value "value"
544 :param key str: the environment variable to set
545 :param value str: the value
547 self.output.write(self.begin+self.setVarEnv+
548 '(r"%s", r"%s", overwrite=True)\n' %
549 (key, self.value_filter(value)))
550 self.environ.set(key,value)
553 def add_comment(self, comment):
554 # Special comment in case of the distène licence
555 if comment=="DISTENE license":
556 self.output.write(self.indent+
560 '(r"%s", r"%s", overwrite=True)\n' %
561 ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
562 self.output.write(self.indent+
566 '(r"%s", r"%s", overwrite=True)\n' %
567 ('DLIM8VAR', '<your licence>'))
569 if "setting environ for" in comment:
570 self.output.write(self.indent+"#[%s]\n" %
571 comment.split("setting environ for ")[1])
574 self.output.write(self.indent+"# %s\n" % comment)
576 def finish(self, required=True):
578 Add a final instruction in the out file (in case of file generation)
579 In the particular launcher case, do nothing
581 :param required bool: Do nothing if required is False
585 class ScreenEnviron(FileEnviron):
586 def __init__(self, output, environ=None):
587 self._do_init(output, environ)
590 def add_line(self, number):
593 def add_comment(self, comment):
596 def add_echo(self, text):
599 def add_warning(self, warning):
602 def write(self, command, name, value, sign="="):
604 self.output.write(" %s%s %s %s %s\n" % \
605 (src.printcolors.printcLabel(command),
606 " " * (12 - len(command)),
607 src.printcolors.printcInfo(name), sign, value))
609 def is_defined(self, name):
610 return name in self.defined
613 return "${%s}" % name
615 def set(self, name, value):
616 self.write("set", name, value)
617 self.defined[name] = value
619 def prepend(self, name, value, sep=":"):
620 if isinstance(value, list):
621 value = sep.join(value)
622 value = value + sep + self.get(name)
623 self.write("prepend", name, value)
625 def append(self, name, value, sep=":"):
626 if isinstance(value, list):
627 value = sep.join(value)
628 value = self.get(name) + sep + value
629 self.write("append", name, value)
631 def run_env_script(self, module, script):
632 self.write("load", script, "", sign="")
634 # The SALOME launcher template
636 #! /usr/bin/env python
638 ################################################################
639 # WARNING: this file is automatically generated by SalomeTools #
640 # WARNING: and so could be overwritten at any time. #
641 ################################################################
648 # Add the pwdPath to able to run the launcher after unpacking a package
649 # Used only in case of a salomeTools package
650 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
652 # Preliminary work to initialize path to SALOME Python modules
655 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
656 os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
658 # define folder to store omniorb config (initially in virtual application folder)
660 from salomeContextUtils import setOmniOrbUserPath
662 except Exception as e:
665 # End of preliminary work
667 # salome doc only works for virtual applications. Therefore we overwrite it with this function
668 def _showDoc(modules):
669 for module in modules:
670 modulePath = os.getenv(module+"_ROOT_DIR")
671 if modulePath != None:
672 baseDir = os.path.join(modulePath, "share", "doc", "salome")
673 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
674 if not os.path.isfile(docfile):
675 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
676 if not os.path.isfile(docfile):
677 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
678 if os.path.isfile(docfile):
679 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
681 print "Online documentation is not accessible for module:", module
683 print module+"_ROOT_DIR not found!"
686 # Identify application path then locate configuration files
689 if args == ['--help']:
690 from salomeContext import usage
694 #from salomeContextUtils import getConfigFileNames
695 #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
696 #if len(unexisting) > 0:
697 # print "ERROR: unexisting configuration file(s): " + ', '.join(unexisting)
700 # Create a SalomeContext which parses configFileNames to initialize environment
702 from salomeContext import SalomeContext, SalomeContextException
703 context = SalomeContext(None)
705 # Here set specific variables, if needed
706 # context.addToPath('mypath')
707 # context.addToLdLibraryPath('myldlibrarypath')
708 # context.addToPythonPath('mypythonpath')
709 # context.setVariable('myvarname', 'value')
712 context.getLogger().setLevel(40)
714 # here your local standalone environment
716 if len(args) >1 and args[0]=='doc':
720 # Start SALOME, parsing command line arguments
721 out, err, status = context.runSalome(args)
724 except SalomeContextException, e:
726 logging.getLogger("salome").error(e)
730 if __name__ == "__main__":
737 #! /usr/bin/env python3
739 ################################################################
740 # WARNING: this file is automatically generated by SalomeTools #
741 # WARNING: and so could be overwritten at any time. #
742 ################################################################
749 # Add the pwdPath to able to run the launcher after unpacking a package
750 # Used only in case of a salomeTools package
751 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
753 # Preliminary work to initialize path to SALOME Python modules
756 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
757 os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
759 # define folder to store omniorb config (initially in virtual application folder)
761 from salomeContextUtils import setOmniOrbUserPath
763 except Exception as e:
766 # End of preliminary work
768 # salome doc only works for virtual applications. Therefore we overwrite it with this function
769 def _showDoc(modules):
770 for module in modules:
771 modulePath = os.getenv(module+"_ROOT_DIR")
772 if modulePath != None:
773 baseDir = os.path.join(modulePath, "share", "doc", "salome")
774 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
775 if not os.path.isfile(docfile):
776 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
777 if not os.path.isfile(docfile):
778 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
779 if os.path.isfile(docfile):
780 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
782 print("Online documentation is not accessible for module:", module)
784 print(module+"_ROOT_DIR not found!")
787 # Identify application path then locate configuration files
790 if args == ['--help']:
791 from salomeContext import usage
795 #from salomeContextUtils import getConfigFileNames
796 #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
797 #if len(unexisting) > 0:
798 # print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
801 # Create a SalomeContext which parses configFileNames to initialize environment
803 from salomeContext import SalomeContext, SalomeContextException
804 context = SalomeContext(None)
806 # Here set specific variables, if needed
807 # context.addToPath('mypath')
808 # context.addToLdLibraryPath('myldlibrarypath')
809 # context.addToPythonPath('mypythonpath')
810 # context.setVariable('myvarname', 'value')
813 context.getLogger().setLevel(40)
815 # here your local standalone environment
817 if len(args) >1 and args[0]=='doc':
821 # Start SALOME, parsing command line arguments
822 out, err, status = context.runSalome(args)
825 except SalomeContextException as e:
827 logging.getLogger("salome").error(e)
831 if __name__ == "__main__":