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
25 def get_file_environ(output, shell, environ=None):
26 """Instantiate correct FileEnvironment sub-class.
28 :param output file: the output file stream.
29 :param shell str: the type of shell syntax to use.
30 :param environ dict: a potential additional environment.
33 environ=src.environment.Environ({})
35 return BashFileEnviron(output, environ)
37 return TclFileEnviron(output, environ)
39 return BatFileEnviron(output, environ)
40 if shell == "cfgForPy":
41 return LauncherFileEnviron(output, environ)
43 return ContextFileEnviron(output, environ)
44 raise Exception("FileEnviron: Unknown shell = %s" % shell)
46 class FileEnviron(object):
48 Base class for shell environment
50 def __init__(self, output, environ=None):
54 :param output file: the output file stream.
55 :param environ dict: SalomeEnviron.
57 self._do_init(output, environ)
61 easy non exhaustive quick resume for debug print"""
63 "output" : self.output,
64 "environ" : self.environ,
66 return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
69 def _do_init(self, output, environ=None):
73 :param output file: the output file stream.
74 :param environ dict: a potential additional environment.
77 self.init_path=True # by default we initialise all paths, except PATH
78 if environ is not None:
79 self.environ = environ
81 self.environ = src.environment.Environ({})
83 def add_line(self, number):
85 Add some empty lines in the shell file
87 :param number int: the number of lines to add
89 self.output.write("\n" * number)
91 def add_comment(self, comment):
93 Add a comment in the shell file
95 :param comment str: the comment to add
97 self.output.write("# %s\n" % comment)
99 def add_echo(self, text):
101 Add a "echo" in the shell file
103 :param text str: the text to echo
105 self.output.write('echo %s"\n' % text)
107 def add_warning(self, warning):
109 Add a warning "echo" in the shell file
111 :param warning str: the text to echo
113 self.output.write('echo "WARNING %s"\n' % warning)
115 def append_value(self, key, value, sep=os.pathsep):
117 append value to key using sep,
118 if value contains ":" or ";" then raise error
120 :param key str: the environment variable to append
121 :param value str: the value to append to key
122 :param sep str: the separator string
124 # check that value so no contain the system separator
126 if separator in value:
127 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
129 if self.environ.is_defined(key):
130 value_list = self.environ.get(key).split(sep)
131 if self.environ._expandvars(value) in value_list:
132 do_append=False # value is already in key path : we don't append it again
135 self.environ.append_value(key, value,sep)
136 self.set(key, self.get(key) + sep + value)
138 def append(self, key, value, sep=os.pathsep):
140 Same as append_value but the value argument can be a list
142 :param key str: the environment variable to append
143 :param value str or list: the value(s) to append to key
144 :param sep str: the separator string
146 if isinstance(value, list):
148 self.append_value(key, v, sep)
150 self.append_value(key, value, sep)
152 def prepend_value(self, key, value, sep=os.pathsep):
154 prepend value to key using sep,
155 if value contains ":" or ";" then raise error
157 :param key str: the environment variable to prepend
158 :param value str: the value to prepend to key
159 :param sep str: the separator string
161 # check that value so no contain the system separator
163 if separator in value:
164 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
167 if self.environ.is_defined(key):
168 value_list = self.environ.get(key).split(sep)
169 exp_val=self.environ._expandvars(value)
170 if exp_val in value_list:
172 if not do_not_prepend:
173 self.environ.prepend_value(key, value,sep)
174 self.set(key, value + sep + self.get(key))
176 def prepend(self, key, value, sep=os.pathsep):
178 Same as prepend_value but the value argument can be a list
180 :param key str: the environment variable to prepend
181 :param value str or list: the value(s) to prepend to key
182 :param sep str: the separator string
184 if isinstance(value, list):
185 for v in reversed(value): # prepend list, first item at last to stay first
186 self.prepend_value(key, v, sep)
188 self.prepend_value(key, value, sep)
190 def is_defined(self, key):
192 Check if the key exists in the environment
194 :param key str: the environment variable to check
196 return self.environ.is_defined(key)
198 def set(self, key, value):
200 Set the environment variable 'key' to value 'value'
202 :param key str: the environment variable to set
203 :param value str: the value
205 raise NotImplementedError("set is not implement for this shell!")
209 Get the value of the environment variable "key"
211 :param key str: the environment variable
213 if src.architecture.is_windows():
214 return '%' + key + '%'
218 def get_value(self, key):
219 """Get the real value of the environment variable "key"
220 It can help env scripts
221 :param key str: the environment variable
223 return self.environ.get_value(key)
226 """Add a final instruction in the out file (in case of file generation)
228 :param required bool: Do nothing if required is False
232 def set_no_init_path(self):
233 """Set the no initialisation mode for all paths.
234 By default only PATH is not reinitialised. All others paths are
235 (LD_LIBRARY_PATH, PYTHONPATH, ...)
236 After the call to these function ALL PATHS ARE NOT REINITIALISED.
237 There initial value is inherited from the environment
241 def value_filter(self, value):
246 class TclFileEnviron(FileEnviron):
250 def __init__(self, output, environ=None):
253 :param output file: the output file stream.
254 :param environ dict: a potential additional environment.
256 self._do_init(output, environ)
257 self.output.write(tcl_header.replace("<module_name>",
258 self.environ.get("sat_product_name")))
259 self.output.write("\nset software %s\n" % self.environ.get("sat_product_name") )
260 self.output.write("set version %s\n" % self.environ.get("sat_product_version") )
261 root=os.path.join(self.environ.get("sat_product_base_path"),
263 self.environ.get("sat_product_base_name"),
266 self.output.write("set root %s\n" % root)
267 modules_to_load=self.environ.get("sat_product_load_depend")
268 if len(modules_to_load)>0:
269 # write module load commands for product dependencies
270 self.output.write("\n")
271 for module_to_load in modules_to_load.split(";"):
272 self.output.write(module_to_load+"\n")
274 def set(self, key, value):
275 """Set the environment variable "key" to value "value"
277 :param key str: the environment variable to set
278 :param value str: the value
280 self.output.write('setenv %s "%s"\n' % (key, value))
281 self.environ.set(key, value)
285 Get the value of the environment variable "key"
287 :param key str: the environment variable
289 return self.environ.get(key)
291 def append_value(self, key, value, sep=os.pathsep):
292 """append value to key using sep
294 :param key str: the environment variable to append
295 :param value str: the value to append to key
296 :param sep str: the separator string
299 self.output.write('append-path %s %s\n' % (key, value))
301 self.output.write('append-path --delim=\%c %s %s\n' % (sep, key, value))
303 def prepend_value(self, key, value, sep=os.pathsep):
304 """prepend value to key using sep
306 :param key str: the environment variable to prepend
307 :param value str: the value to prepend to key
308 :param sep str: the separator string
311 self.output.write('prepend-path %s %s\n' % (key, value))
313 self.output.write('prepend-path --delim=\%c %s %s\n' % (sep, key, value))
316 class BashFileEnviron(FileEnviron):
318 Class for bash 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(bash_header)
329 def set(self, key, value):
330 """Set the environment variable "key" to value "value"
332 :param key str: the environment variable to set
333 :param value str: the value
335 self.output.write('export %s="%s"\n' % (key, value))
336 self.environ.set(key, value)
340 class BatFileEnviron(FileEnviron):
342 for Windows batch shell.
344 def __init__(self, output, environ=None):
347 :param output file: the output file stream.
348 :param environ dict: a potential additional environment.
350 self._do_init(output, environ)
351 self.output.write(bat_header)
353 def add_comment(self, comment):
354 """Add a comment in the shell file
356 :param comment str: the comment to add
358 self.output.write("rem %s\n" % comment)
361 """Get the value of the environment variable "key"
363 :param key str: the environment variable
365 return '%%%s%%' % key
367 def set(self, key, value):
368 """Set the environment variable "key" to value "value"
370 :param key str: the environment variable to set
371 :param value str: the value
373 self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
374 self.environ.set(key, value)
377 class ContextFileEnviron(FileEnviron):
378 """Class for a salome context configuration file.
380 def __init__(self, output, environ=None):
383 :param output file: the output file stream.
384 :param environ dict: a potential additional environment.
386 self._do_init(output, environ)
387 self.output.write(cfg_header)
389 def set(self, key, value):
390 """Set the environment variable "key" to value "value"
392 :param key str: the environment variable to set
393 :param value str: the value
395 self.output.write('%s="%s"\n' % (key, value))
396 self.environ.set(key, value)
399 """Get the value of the environment variable "key"
401 :param key str: the environment variable
403 return '%({0})s'.format(key)
405 def add_echo(self, text):
408 :param text str: the comment to add
410 self.add_comment(text)
412 def add_warning(self, warning):
415 :param text str: the warning to add
417 self.add_comment("WARNING %s" % warning)
419 def prepend_value(self, key, value, sep=os.pathsep):
420 """prepend value to key using sep
422 :param key str: the environment variable to prepend
423 :param value str: the value to prepend to key
424 :param sep str: the separator string
427 if self.environ.is_defined(key):
428 value_list = self.environ.get(key).split(sep)
429 #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
430 if value in value_list:
431 do_append=False # value is already in key path : we don't append it again
434 self.environ.append_value(key, value,sep)
435 self.output.write('ADD_TO_%s: %s\n' % (key, value))
437 def append_value(self, key, value, sep=os.pathsep):
438 """append value to key using sep
440 :param key str: the environment variable to append
441 :param value str: the value to append to key
442 :param sep str: the separator string
444 self.prepend_value(key, value)
447 class LauncherFileEnviron(FileEnviron):
449 Class to generate a launcher file script
450 (in python syntax) SalomeContext API
452 def __init__(self, output, environ=None):
455 :param output file: the output file stream.
456 :param environ dict: a potential additional environment.
458 self._do_init(output, environ)
459 self.python_version=self.environ.get("sat_python_version")
460 self.bin_kernel_root_dir=self.environ.get("sat_bin_kernel_install_dir")
462 # four whitespaces for first indentation in a python script
464 self.prefix="context."
465 self.setVarEnv="setVariable"
466 self.begin=self.indent+self.prefix
468 # write the begining of launcher file.
469 # choose the template version corresponding to python version
470 # and substitute BIN_KERNEL_INSTALL_DIR (the path to salomeContext.py)
471 if self.python_version == 2:
472 launcher_header=launcher_header2
474 launcher_header=launcher_header3
475 # in case of Windows OS, Python scripts are not executable. PyExe ?
476 if src.architecture.is_windows():
477 launcher_header = launcher_header.replace("#! /usr/bin/env python3",'')
478 self.output.write(launcher_header\
479 .replace("BIN_KERNEL_INSTALL_DIR", self.bin_kernel_root_dir))
481 # for these path, we use specialired functions in salomeContext api
482 self.specialKeys={"PATH": "Path",
483 "LD_LIBRARY_PATH": "LdLibraryPath",
484 "PYTHONPATH": "PythonPath"}
486 # we do not want to reinitialise PATH.
487 # for that we make sure PATH is in self.environ
488 # and therefore we will not use setVariable for PATH
489 if not self.environ.is_defined("PATH"):
490 self.environ.set("PATH","")
492 def add_echo(self, text):
495 :param text str: the comment to add
497 self.output.write('# %s"\n' % text)
499 def add_warning(self, warning):
502 :param text str: the warning to add
504 self.output.write('# "WARNING %s"\n' % warning)
506 def append_value(self, key, value, sep=os.pathsep):
507 """append value to key using sep,
508 if value contains ":" or ";" then raise error
510 :param key str: the environment variable to prepend
511 :param value str: the value to prepend to key
512 :param sep str: the separator string
514 # check that value so no contain the system separator
516 msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
517 if separator in value:
518 raise Exception(msg % (key, value, separator))
520 is_key_defined=self.environ.is_defined(key)
521 conditional_reinit=False
522 if (self.init_path and (not is_key_defined)):
523 # reinitialisation mode set to true (the default)
524 # for the first occurrence of key, we set it.
525 # therefore key will not be inherited from environment
526 self.output.write(self.indent+'if reinitialise_paths:\n'+self.indent)
528 self.output.write(self.indent+'else:\n'+self.indent)
529 conditional_reinit=True # in this case do not register value in self.environ a second time
531 # in all other cases we use append (except if value is already the key
534 value_list = self.environ.get(key).split(sep)
535 # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
536 if value in value_list:
537 do_append=False # value is already in key path : we don't append it again
540 if not conditional_reinit:
541 self.environ.append_value(key, value,sep) # register value in self.environ
542 if key in self.specialKeys.keys():
543 #for these special keys we use the specific salomeContext function
544 self.output.write(self.begin+'addTo%s(r"%s")\n' %
545 (self.specialKeys[key], self.value_filter(value)))
547 # else we use the general salomeContext addToVariable function
548 self.output.write(self.begin+'appendVariable(r"%s", r"%s",separator="%s")\n'
549 % (key, self.value_filter(value), sep))
551 def append(self, key, value, sep=":"):
552 """Same as append_value but the value argument can be a list
554 :param key str: the environment variable to append
555 :param value str or list: the value(s) to append to key
556 :param sep str: the separator string
558 if isinstance(value, list):
560 self.append_value(key, v, sep)
562 self.append_value(key, value, sep)
564 def prepend_value(self, key, value, sep=os.pathsep):
565 """prepend value to key using sep,
566 if value contains ":" or ";" then raise error
568 :param key str: the environment variable to prepend
569 :param value str: the value to prepend to key
570 :param sep str: the separator string
572 # check that value so no contain the system separator
574 msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
575 if separator in value:
576 raise Exception(msg % (key, value, separator))
578 is_key_defined=self.environ.is_defined(key)
579 conditional_reinit=False
580 if (self.init_path and (not is_key_defined)):
581 # reinitialisation mode set to true (the default)
582 # for the first occurrence of key, we set it.
583 # therefore key will not be inherited from environment
584 self.output.write(self.indent+'if reinitialise_paths:\n'+self.indent)
586 self.output.write(self.indent+'else:\n'+self.indent)
587 conditional_reinit=True # in this case do not register value in self.environ a second time
589 # in all other cases we use append (except if value is already the key
592 value_list = self.environ.get(key).split(sep)
593 # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
594 if value in value_list:
595 do_append=False # value is already in key path : we don't append it again
598 if not conditional_reinit:
599 self.environ.append_value(key, value,sep) # register value in self.environ
600 if key in self.specialKeys.keys():
601 #for these special keys we use the specific salomeContext function
602 self.output.write(self.begin+'addTo%s(r"%s")\n' %
603 (self.specialKeys[key], self.value_filter(value)))
605 # else we use the general salomeContext addToVariable function
606 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n'
607 % (key, self.value_filter(value), sep))
610 def prepend(self, key, value, sep=":"):
611 """Same as prepend_value but the value argument can be a list
613 :param key str: the environment variable to prepend
614 :param value str or list: the value(s) to prepend to key
615 :param sep str: the separator string
617 if isinstance(value, list):
619 self.prepend_value(key, v, sep)
621 self.prepend_value(key, value, sep)
624 def set(self, key, value):
625 """Set the environment variable "key" to value "value"
627 :param key str: the environment variable to set
628 :param value str: the value
630 self.output.write(self.begin+self.setVarEnv+
631 '(r"%s", r"%s", overwrite=True)\n' %
632 (key, self.value_filter(value)))
633 self.environ.set(key,value)
636 def add_comment(self, comment):
637 # Special comment in case of the DISTENE licence
638 if comment=="DISTENE license":
639 self.output.write(self.indent+
643 '(r"%s", r"%s", overwrite=True)\n' %
644 ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
645 self.output.write(self.indent+
649 '(r"%s", r"%s", overwrite=True)\n' %
650 ('DLIM8VAR', '<your licence>'))
652 if "setting environ for" in comment:
653 self.output.write(self.indent+"#[%s]\n" %
654 comment.split("setting environ for ")[1])
657 self.output.write(self.indent+"# %s\n" % comment)
661 Add a final instruction in the out file (in case of file generation)
662 In the particular launcher case, do nothing
664 :param required bool: Do nothing if required is False
666 if self.python_version == 2:
667 launcher_tail=launcher_tail_py2
669 launcher_tail=launcher_tail_py3
670 self.output.write(launcher_tail)
673 class ScreenEnviron(FileEnviron):
674 def __init__(self, output, environ=None):
675 self._do_init(output, environ)
678 def add_line(self, number):
681 def add_comment(self, comment):
684 def add_echo(self, text):
687 def add_warning(self, warning):
690 def write(self, command, name, value, sign="="):
692 self.output.write(" %s%s %s %s %s\n" % \
693 (src.printcolors.printcLabel(command),
694 " " * (12 - len(command)),
695 src.printcolors.printcInfo(name), sign, value))
697 def is_defined(self, name):
698 return name in self.defined
701 return "${%s}" % name
703 def set(self, name, value):
704 self.write("set", name, value)
705 self.defined[name] = value
707 def prepend(self, name, value, sep=":"):
708 if isinstance(value, list):
709 value = sep.join(value)
710 value = value + sep + self.get(name)
711 self.write("prepend", name, value)
713 def append(self, name, value, sep=":"):
714 if isinstance(value, list):
715 value = sep.join(value)
716 value = self.get(name) + sep + value
717 self.write("append", name, value)
719 def run_env_script(self, module, script):
720 self.write("load", script, "", sign="")
729 rem The following variables are used only in case of a sat package
730 set out_dir_Path=%~dp0
736 # <module_name> module for use with 'environment-modules' package
744 # check that the user is not using another shell
746 echo "Warning! SALOME environment not initialized"
747 echo "You must run this script in a BASH shell."
748 echo "As you are using another shell. Please first run: bash"
752 ##########################################################################
754 # This line is used only in case of a sat package
755 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
757 ###########################################################################
761 [SALOME Configuration]
764 launcher_header2="""\
765 #! /usr/bin/env python
767 ################################################################
768 # WARNING: this file is automatically generated by SalomeTools #
769 # WARNING: and so could be overwritten at any time. #
770 ################################################################
777 # Add the pwdPath to able to run the launcher after unpacking a package
778 # Used only in case of a salomeTools package
779 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
781 # Preliminary work to initialize path to SALOME Python modules
784 sys.path[:0] = [ r'BIN_KERNEL_INSTALL_DIR' ] # to get salomeContext
786 # define folder to store omniorb config (initially in virtual application folder)
788 from salomeContextUtils import setOmniOrbUserPath
790 except Exception as e:
793 # End of preliminary work
795 # salome doc only works for virtual applications. Therefore we overwrite it with this function
796 def _showDoc(modules):
797 for module in modules:
798 modulePath = os.getenv(module+"_ROOT_DIR")
799 if modulePath != None:
800 baseDir = os.path.join(modulePath, "share", "doc", "salome")
801 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
802 if not os.path.isfile(docfile):
803 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
804 if not os.path.isfile(docfile):
805 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
806 if os.path.isfile(docfile):
807 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
809 print ("Online documentation is not accessible for module:", module)
811 print (module+"_ROOT_DIR not found!")
814 # Identify application path then locate configuration files
817 if args == ['--help']:
818 from salomeContext import usage
819 appended_opt_doc = \"""
822 With this option the environment variables PATH, PYTHONPATH and LD_LIBRARY_PATH defined into the starting shell are kept.
823 Without this option all values set before starting SALOME are simply ignored.
825 usage(appended_opt_doc=appended_opt_doc)
828 reinitialise_paths=True
829 if '--keep-paths' in args:
830 reinitialise_paths=False
831 args.remove('--keep-paths')
834 # Create a SalomeContext which parses configFileNames to initialize environment
836 from salomeContext import SalomeContext, SalomeContextException
837 if 'appendVariable' not in dir(SalomeContext):
838 # check whether the appendVariable method is implemented
839 def appendVariable(self, name, value, separator=os.pathsep):
842 value = os.path.expandvars(value) # expand environment variables
843 env = os.getenv(name, None)
845 os.environ[name] = value
847 os.environ[name] = env + separator + value
849 SalomeContext.appendVariable = appendVariable
851 context = SalomeContext(None)
853 # Here set specific variables, if needed
854 # context.addToPath('mypath')
855 # context.addToLdLibraryPath('myldlibrarypath')
856 # context.addToPythonPath('mypythonpath')
857 # context.setVariable('myvarname', 'value')
860 context.getLogger().setLevel(40)
863 launcher_header3="""\
864 #! /usr/bin/env python3
866 ################################################################
867 # WARNING: this file is automatically generated by SalomeTools #
868 # WARNING: and so could be overwritten at any time. #
869 ################################################################
876 # Add the pwdPath to able to run the launcher after unpacking a package
877 # Used only in case of a salomeTools package
878 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
880 # Preliminary work to initialize path to SALOME Python modules
883 sys.path[:0] = [ r'BIN_KERNEL_INSTALL_DIR' ]
885 # define folder to store omniorb config (initially in virtual application folder)
887 from salomeContextUtils import setOmniOrbUserPath
889 except Exception as e:
892 # End of preliminary work
894 # salome doc only works for virtual applications. Therefore we overwrite it with this function
895 def _showDoc(modules):
896 for module in modules:
897 modulePath = os.getenv(module+"_ROOT_DIR")
898 if modulePath != None:
899 baseDir = os.path.join(modulePath, "share", "doc", "salome")
900 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
901 if not os.path.isfile(docfile):
902 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
903 if not os.path.isfile(docfile):
904 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
905 if os.path.isfile(docfile):
906 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
908 print("Online documentation is not accessible for module:", module)
910 print(module+"_ROOT_DIR not found!")
913 # Identify application path then locate configuration files
917 from salomeContext import usage
918 appended_opt_doc = \"""
921 With this option the environment variables PATH, PYTHONPATH and LD_LIBRARY_PATH defined into the starting shell are kept.
922 Without this option all values set before starting SALOME are simply ignored.
924 usage(appended_opt_doc=appended_opt_doc)
927 reinitialise_paths=True
928 if '--keep-paths' in args:
929 reinitialise_paths=False
930 args.remove('--keep-paths')
932 #from salomeContextUtils import getConfigFileNames
933 #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
934 #if len(unexisting) > 0:
935 # print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
938 # Create a SalomeContext which parses configFileNames to initialize environment
940 from salomeContext import SalomeContext, SalomeContextException
941 if 'appendVariable' not in dir(SalomeContext):
942 # check whether the appendVariable method is implemented
943 def appendVariable(self, name, value, separator=os.pathsep):
946 value = os.path.expandvars(value) # expand environment variables
947 env = os.getenv(name, None)
949 os.environ[name] = value
951 os.environ[name] = env + separator + value
953 SalomeContext.appendVariable = appendVariable
955 context = SalomeContext(None)
956 # Here set specific variables, if needed
957 # context.addToPath('mypath')
958 # context.addToLdLibraryPath('myldlibrarypath')
959 # context.addToPythonPath('mypythonpath')
960 # context.setVariable('myvarname', 'value')
963 context.getLogger().setLevel(40)
966 launcher_tail_py2="""\
967 #[hook to integrate in launcher additionnal user modules]
969 # Load all files extra.env.d/*.py and call the module's init routine]
971 extradir=out_dir_Path + r"/extra.env.d"
973 if os.path.exists(extradir):
975 sys.path.insert(0, os.path.join(os.getcwd(), extradir))
976 for filename in sorted(
977 filter(lambda x: os.path.isfile(os.path.join(extradir, x)),
978 os.listdir(extradir))):
980 if filename.endswith(".py"):
981 f = os.path.join(extradir, filename)
982 module_name = os.path.splitext(os.path.basename(f))[0]
983 fp, path, desc = imp.find_module(module_name)
984 module = imp.load_module(module_name, fp, path, desc)
985 module.init(context, out_dir_Path)
987 #[manage salome doc command]
988 if len(args) >1 and args[0]=='doc':
992 # Start SALOME, parsing command line arguments
993 out, err, status = context.runSalome(args)
996 except SalomeContextException, e:
998 logging.getLogger("salome").error(e)
1001 if __name__ == "__main__":
1007 launcher_tail_py3="""\
1008 #[hook to integrate in launcher additionnal user modules]
1010 # Load all files extra.env.d/*.py and call the module's init routine]
1012 extradir=out_dir_Path + r"/extra.env.d"
1014 if os.path.exists(extradir):
1016 import importlib.util
1017 sys.path.insert(0, os.path.join(os.getcwd(), extradir))
1018 for filename in sorted(
1019 filter(lambda x: os.path.isfile(os.path.join(extradir, x)),
1020 os.listdir(extradir))):
1022 if filename.endswith(".py"):
1023 f = os.path.join(extradir, filename)
1024 module_name = os.path.splitext(os.path.basename(f))[0]
1025 _specs = importlib.util.find_spec(module_name)
1026 _module = importlib.util.module_from_spec(_specs)
1027 _specs.loader.exec_module(_module)
1028 _module.init(context, out_dir_Path)
1029 #[manage salome doc command]
1030 if len(args) >1 and args[0]=='doc':
1034 # Start SALOME, parsing command line arguments
1035 out, err, status = context.runSalome(args)
1038 except SalomeContextException as e:
1040 logging.getLogger("salome").error(e)
1044 if __name__ == "__main__":