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
26 rem The following variables are used only in case of a sat package
27 set out_dir_Path=%~dp0
28 set PRODUCT_OUT_DIR=%out_dir_Path%
29 set prereq_install_Path=%out_dir_Path%\PREREQUISITES\INSTALL
30 set prereq_build_Path=%out_dir_Path%\PREREQUISITES\BUILD
36 ##########################################################################
39 # cleanup a path (first parameter) from duplicated entries;
40 # second parameter is the separator
42 out_var=`echo $1 | awk -v sep=$2 '{ \\
43 na = split($1,a,sep); \\
45 for(i=0;i<=na;i++) { \\
62 }' | sed -e 's|\\(.*\\)$1|\\1|g' -e 's|^[:;]||' -e 's|[:;]$||'`
69 out_var=`cleandup $xenv $2`
73 # The 3 following variables are used only in case of a sat package
74 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
75 export PRODUCT_OUT_DIR=${out_dir_Path}
76 export PRODUCT_ROOT_DIR=${PRODUCT_OUT_DIR}
78 ###########################################################################
82 [SALOME Configuration]
86 # a generated SALOME Configuration file using python syntax
89 def get_file_environ(output, shell, environ=None):
90 """Instantiate correct FileEnvironment sub-class.
92 :param output file: the output file stream.
93 :param shell str: the type of shell syntax to use.
94 :param environ dict: a potential additional environment.
97 return BashFileEnviron(output, environ)
99 return BatFileEnviron(output, environ)
100 if shell == "cfgForPy":
101 return LauncherFileEnviron(output, environ)
103 return ContextFileEnviron(output, environ)
104 raise Exception("FileEnviron: Unknown shell = %s" % shell)
106 class FileEnviron(object):
108 Base class for shell environment
110 def __init__(self, output, environ=None):
114 :param output file: the output file stream.
115 :param environ dict: a potential additional environment.
117 self._do_init(output, environ)
121 easy non exhaustive quick resume for debug print"""
123 "output" : self.output,
124 "environ" : self.environ,
126 return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
129 def _do_init(self, output, environ=None):
133 :param output file: the output file stream.
134 :param environ dict: a potential additional environment.
138 if environ is not None:
139 #if str(type(environ)) == "<type 'instance'>":
140 if id(environ) == id(os.environ):
141 DBG.tofix("set %s environ as python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
142 self.environ = environ
144 DBG.tofix("set %s environ as COPY of python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
145 self.environ = dict(os.environ) #make a copy cvw 180320
147 def add_line(self, number):
149 Add some empty lines in the shell file
151 :param number int: the number of lines to add
153 self.output.write("\n" * number)
155 def add_comment(self, comment):
157 Add a comment in the shell file
159 :param comment str: the comment to add
161 self.output.write("# %s\n" % comment)
163 def add_echo(self, text):
165 Add a "echo" in the shell file
167 :param text str: the text to echo
169 self.output.write('echo %s"\n' % text)
171 def add_warning(self, warning):
173 Add a warning "echo" in the shell file
175 :param warning str: the text to echo
177 self.output.write('echo "WARNING %s"\n' % warning)
179 def append_value(self, key, value, sep=os.pathsep):
181 append value to key using sep
183 :param key str: the environment variable to append
184 :param value str: the value to append to key
185 :param sep str: the separator string
187 self.set(key, self.get(key) + sep + value)
188 if (key, sep) not in self.toclean:
189 self.toclean.append((key, sep))
191 def append(self, key, value, sep=os.pathsep):
193 Same as append_value but the value argument can be a list
195 :param key str: the environment variable to append
196 :param value str or list: the value(s) to append to key
197 :param sep str: the separator string
199 if isinstance(value, list):
200 self.append_value(key, sep.join(value), sep)
202 self.append_value(key, value, sep)
204 def prepend_value(self, key, value, sep=os.pathsep):
206 prepend value to key using sep
208 :param key str: the environment variable to prepend
209 :param value str: the value to prepend to key
210 :param sep str: the separator string
212 self.set(key, value + sep + self.get(key))
213 if (key, sep) not in self.toclean:
214 self.toclean.append((key, sep))
216 def prepend(self, key, value, sep=os.pathsep):
218 Same as prepend_value but the value argument can be a list
220 :param key str: the environment variable to prepend
221 :param value str or list: the value(s) to prepend to key
222 :param sep str: the separator string
224 if isinstance(value, list):
225 self.prepend_value(key, sep.join(value), sep)
227 self.prepend_value(key, value, sep)
229 def is_defined(self, key):
231 Check if the key exists in the environment
233 :param key str: the environment variable to check
235 return (key in self.environ)
237 def set(self, key, value):
239 Set the environment variable 'key' to value 'value'
241 :param key str: the environment variable to set
242 :param value str: the value
244 raise NotImplementedError("set is not implement for this shell!")
248 Get the value of the environment variable "key"
250 :param key str: the environment variable
254 def command_value(self, key, command):
256 Get the value given by the system command "command"
257 and put it in the environment variable key.
258 Has to be overwritten in the derived classes
259 This can be seen as a virtual method
261 :param key str: the environment variable
262 :param command str: the command to execute
264 raise NotImplementedError("command_value is not implement "
267 def finish(self, required=True):
268 """Add a final instruction in the out file (in case of file generation)
270 :param required bool: Do nothing if required is False
272 for (key, sep) in self.toclean:
274 self.output.write('clean %s "%s"\n' % (key, sep))
276 class BashFileEnviron(FileEnviron):
278 Class for bash shell.
280 def __init__(self, output, environ=None):
283 :param output file: the output file stream.
284 :param environ dict: a potential additional environment.
286 self._do_init(output, environ)
287 self.output.write(bash_header)
289 def set(self, key, value):
290 """Set the environment variable "key" to value "value"
292 :param key str: the environment variable to set
293 :param value str: the value
295 self.output.write('export %s="%s"\n' % (key, value))
296 self.environ[key] = value
298 def command_value(self, key, command):
300 Get the value given by the system command "command"
301 and put it in the environment variable key.
302 Has to be overwritten in the derived classes
303 This can be seen as a virtual method
305 :param key str: the environment variable
306 :param command str: the command to execute
308 self.output.write('export %s=$(%s)\n' % (key, command))
310 def finish(self, required=True):
311 """Add a final instruction in the out file (in case of file generation)
313 :param required bool: Do nothing if required is False
317 FileEnviron.finish(self, required)
319 class BatFileEnviron(FileEnviron):
321 for Windows batch shell.
323 def __init__(self, output, environ=None):
326 :param output file: the output file stream.
327 :param environ dict: a potential additional environment.
329 self._do_init(output, environ)
330 self.output.write(bat_header)
332 def add_comment(self, comment):
333 """Add a comment in the shell file
335 :param comment str: the comment to add
337 self.output.write("rem %s\n" % comment)
340 """Get the value of the environment variable "key"
342 :param key str: the environment variable
344 return '%%%s%%' % key
346 def set(self, key, value):
347 """Set the environment variable "key" to value "value"
349 :param key str: the environment variable to set
350 :param value str: the value
352 self.output.write('set %s=%s\n' % (key, value))
353 self.environ[key] = value
355 def command_value(self, key, command):
357 Get the value given by the system command "command"
358 and put it in the environment variable key.
359 Has to be overwritten in the derived classes
360 This can be seen as a virtual method
362 :param key str: the environment variable
363 :param command str: the command to execute
365 self.output.write('%s > tmp.txt\n' % (command))
366 self.output.write('set /p %s =< tmp.txt\n' % (key))
368 def finish(self, required=True):
370 Add a final instruction in the out file (in case of file generation)
371 In the particular windows case, do nothing
373 :param required bool: Do nothing if required is False
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[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 command_value(self, key, command):
407 Get the value given by the system command "command"
408 and put it in the environment variable key.
409 Has to be overwritten in the derived classes
410 This can be seen as a virtual method
412 :param key str: the environment variable
413 :param command str: the command to execute
415 raise NotImplementedError("command_value is not implement "
416 "for salome context files!")
418 def add_echo(self, text):
421 :param text str: the comment to add
423 self.add_comment(text)
425 def add_warning(self, warning):
428 :param text str: the warning to add
430 self.add_comment("WARNING %s" % warning)
432 def prepend_value(self, key, value, sep=os.pathsep):
433 """prepend value to key using sep
435 :param key str: the environment variable to prepend
436 :param value str: the value to prepend to key
437 :param sep str: the separator string
439 self.output.write('ADD_TO_%s: %s\n' % (key, value))
441 def append_value(self, key, value, sep=os.pathsep):
442 """append value to key using sep
444 :param key str: the environment variable to append
445 :param value str: the value to append to key
446 :param sep str: the separator string
448 self.prepend_value(key, value)
450 def finish(self, required=True):
451 """Add a final instruction in the out file (in case of file generation)
453 :param required bool: Do nothing if required is False
457 def special_path_separator(name):
459 TCLLIBPATH, TKLIBPATH, PV_PLUGIN_PATH environments variables need
460 some exotic path separator.
461 This function gives the separator regarding the name of the variable
462 to append or prepend.
464 :param name str: The name of the variable to find the separator
466 special_blanks_keys=["TCLLIBPATH", "TKLIBPATH"]
467 special_semicolon_keys=["PV_PLUGIN_PATH"]
469 if name in special_blanks_keys: res=" "
470 if name in special_semicolon_keys: res=";"
473 class LauncherFileEnviron:
475 Class to generate a launcher file script
476 (in python syntax) SalomeContext API
478 def __init__(self, output, environ=None):
481 :param output file: the output file stream.
482 :param environ dict: a potential additional environment.
486 if environ is not None:
487 self.environ = environ
489 self.environ = os.environ
490 # Initialize some variables
491 if not "PATH" in self.environ.keys():
492 self.environ["PATH"]=""
493 if not "LD_LIBRARY_PATH" in self.environ.keys():
494 self.environ["LD_LIBRARY_PATH"]=""
495 if not "PYTHONPATH" in self.environ.keys():
496 self.environ["PYTHONPATH"]=""
497 if not "TCLLIBPATH" in self.environ.keys():
498 self.environ["TCLLIBPATH"]=""
499 if not "TKLIBPATH" in self.environ.keys():
500 self.environ["TKLIBPATH"]=""
502 # four whitespaces for first indentation in a python script
504 self.prefix="context."
505 self.setVarEnv="setVariable"
507 self.begin=self.indent+self.prefix
508 self.output.write(Launcher_header)
509 self.specialKeys={"PATH": "Path",
510 "LD_LIBRARY_PATH": "LdLibraryPath",
511 "PYTHONPATH": "PythonPath"}
513 def change_to_launcher(self, value):
517 def add_line(self, number):
518 """Add some empty lines in the launcher file
520 :param number int: the number of lines to add
522 self.output.write("\n" * number)
524 def add_echo(self, text):
527 :param text str: the comment to add
529 self.output.write('# %s"\n' % text)
531 def add_warning(self, warning):
534 :param text str: the warning to add
536 self.output.write('# "WARNING %s"\n' % warning)
538 def append_value(self, key, value, sep=":"):
539 """append value to key using sep
541 :param key str: the environment variable to append
542 :param value str: the value to append to key
543 :param sep str: the separator string
545 if self.is_defined(key) :
550 def append(self, key, value, sep=":"):
551 """Same as append_value but the value argument can be a list
553 :param key str: the environment variable to append
554 :param value str or list: the value(s) to append to key
555 :param sep str: the separator string
557 if isinstance(value, list):
558 self.append_value(key, sep.join(value), sep)
560 self.append_value(key, value, sep)
562 def prepend_value(self, key, value, sep=":"):
563 """prepend value to key using sep
565 :param key str: the environment variable to prepend
566 :param value str: the value to prepend to key
567 :param sep str: the separator string
569 if self.is_defined(key) :
574 def prepend(self, key, value, sep=":"):
575 """Same as prepend_value but the value argument can be a list
577 :param key str: the environment variable to prepend
578 :param value str or list: the value(s) to prepend to key
579 :param sep str: the separator string
581 if isinstance(value, list):
582 self.prepend_value(key, sep.join(value), sep)
584 self.prepend_value(key, value, sep)
586 def is_defined(self, key):
587 """Check if the key exists in the environment
589 :param key str: the environment variable to check
591 return key in self.environ.keys()
594 """Get the value of the environment variable "key"
596 :param key str: the environment variable
600 def set(self, key, value):
601 """Set the environment variable "key" to value "value"
603 :param key str: the environment variable to set
604 :param value str: the value
606 self.output.write(self.begin+self.setVarEnv+
607 '(r"%s", r"%s", overwrite=True)\n' %
608 (key, self.change_to_launcher(value)))
609 self.environ[key] = value
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
633 def command_value(self, key, command):
635 Get the value given by the system command "command"
636 and put it in the environment variable key.
638 :param key str: the environment variable
639 :param command str: the command to execute
641 self.output.write(self.indent+'#`%s`\n' % command)
643 import shlex, subprocess
644 args = shlex.split(command)
645 res=subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
646 out, __ = res.communicate()
647 self.output.write(self.begin+
649 '(r"%s", r"%s", overwrite=True)\n' % (key, out))
651 def add_comment(self, comment):
652 # Special comment in case of the distène licence
653 if comment=="DISTENE license":
654 self.output.write(self.indent+
658 '(r"%s", r"%s", overwrite=True)\n' %
659 ('DISTENE_LICENSE_FILE',
660 self.change_to_launcher(
661 'Use global envvar: DLIM8VAR')))
662 self.output.write(self.indent+
666 '(r"%s", r"%s", overwrite=True)\n' %
668 self.change_to_launcher(
671 if "setting environ for" in comment:
672 self.output.write(self.indent+"#[%s]\n" %
673 comment.split("setting environ for ")[1])
676 self.output.write(self.indent+"# %s\n" % comment)
678 def finish(self, required=True):
680 Add a final instruction in the out file (in case of file generation)
681 In the particular launcher case, do nothing
683 :param required bool: Do nothing if required is False
687 class ScreenEnviron(FileEnviron):
688 def __init__(self, output, environ=None):
689 self._do_init(output, environ)
692 def add_line(self, number):
695 def add_comment(self, comment):
698 def add_echo(self, text):
701 def add_warning(self, warning):
704 def write(self, command, name, value, sign="="):
706 self.output.write(" %s%s %s %s %s\n" % \
707 (src.printcolors.printcLabel(command),
708 " " * (12 - len(command)),
709 src.printcolors.printcInfo(name), sign, value))
711 def is_defined(self, name):
712 return self.defined.has_key(name)
715 return "${%s}" % name
717 def set(self, name, value):
718 self.write("set", name, value)
719 self.defined[name] = value
721 def prepend(self, name, value, sep=":"):
722 if isinstance(value, list):
723 value = sep.join(value)
724 value = value + sep + self.get(name)
725 self.write("prepend", name, value)
727 def append(self, name, value, sep=":"):
728 if isinstance(value, list):
729 value = sep.join(value)
730 value = self.get(name) + sep + value
731 self.write("append", name, value)
733 def command_value(self, key, command):
736 def run_env_script(self, module, script):
737 self.write("load", script, "", sign="")
739 # The SALOME launcher template
741 #! /usr/bin/env python
743 ################################################################
744 # WARNING: this file is automatically generated by SalomeTools #
745 # WARNING: and so could be overwritten at any time. #
746 ################################################################
753 # Add the pwdPath to able to run the launcher after unpacking a package
754 # Used only in case of a salomeTools package
755 out_dir_Path=os.path.abspath(os.path.dirname(__file__))
757 # Preliminary work to initialize path to SALOME Python modules
760 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
761 os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
763 # define folder to store omniorb config (initially in virtual application folder)
765 from salomeContextUtils import setOmniOrbUserPath
770 # End of preliminary work
772 # salome doc only works for virtual applications. Therefore we overwrite it with this function
773 def _showDoc(modules):
774 for module in modules:
775 modulePath = os.getenv(module+"_ROOT_DIR")
776 if modulePath != None:
777 baseDir = os.path.join(modulePath, "share", "doc", "salome")
778 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
779 if not os.path.isfile(docfile):
780 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
781 if not os.path.isfile(docfile):
782 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
783 if os.path.isfile(docfile):
784 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
786 print "Online documentation is not accessible for module:", module
788 print module+"_ROOT_DIR not found!"
791 # Identify application path then locate configuration files
794 if args == ['--help']:
795 from salomeContext import usage
799 #from salomeContextUtils import getConfigFileNames
800 #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
801 #if len(unexisting) > 0:
802 # print "ERROR: unexisting configuration file(s): " + ', '.join(unexisting)
805 # Create a SalomeContext which parses configFileNames to initialize environment
807 from salomeContext import SalomeContext, SalomeContextException
808 SalomeContext.addToSpecial=addToSpecial
809 context = SalomeContext(None)
811 # Here set specific variables, if needed
812 # context.addToPath('mypath')
813 # context.addToLdLibraryPath('myldlibrarypath')
814 # context.addToPythonPath('mypythonpath')
815 # context.setVariable('myvarname', 'value')
818 context.getLogger().setLevel(40)
820 context.setVariable(r"PRODUCT_ROOT_DIR", out_dir_Path, overwrite=True)
821 # here your local standalone environment
823 if len(args) >1 and args[0]=='doc':
827 # Start SALOME, parsing command line arguments
828 out, err, status = context.runSalome(args)
831 except SalomeContextException, e:
833 logging.getLogger("salome").error(e)
836 def addToSpecial(self, name, value, pathSep=None):
837 # add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc...
838 # http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
839 # TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
843 specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
844 specialSemicolonKeys=["PV_PLUGIN_PATH"]
846 if name in specialBlanksKeys: res=" "
847 if name in specialSemicolonKeys: res=";"
853 value = os.path.expandvars(value) # expand environment variables
854 self.getLogger().debug("Add to %s: %s", name, value)
855 env = os.getenv(name, None)
857 os.environ[name] = value
859 os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
861 if __name__ == "__main__":