1 # Copyright (C) 2013-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
25 from parseConfigFile import parseConfigFile
32 from salomeContextUtils import SalomeContextException
36 Usage: salome [command] [options] [--config=<file,folder,...>]
40 start Start a new SALOME instance.
41 context Initialize SALOME context. Current environment is extended.
42 shell Initialize SALOME context, attached to the last created SALOME
43 instance if any, and executes scripts passed as command arguments.
44 User works in a Shell terminal. SALOME environment is set but
45 application is not started.
46 connect Connect a Python console to the active SALOME instance.
47 kill <port(s)> Terminate SALOME instances running on given ports for current user.
48 Port numbers must be separated by blank characters.
49 killall Terminate *all* SALOME running instances for current user.
50 Do not start a new one.
51 test Run SALOME tests.
52 info Display some information about SALOME.
53 doc <module(s)> Show online module documentation (if available).
54 Module names must be separated by blank characters.
55 help Show this message.
57 If no command is given, default is start.
61 Use salome <command> --help to show help on command. Available for the
62 following commands: start, shell, connect, test, info.
64 --config=<file,folder,...>
65 ==========================
66 Initialize SALOME context from a list of context files and/or a list
67 of folders containing context files. The list is comma-separated, whithout
75 The SalomeContext class in an API to configure SALOME context then
76 start SALOME using a single python command.
81 Initialize context from a list of configuration files
82 identified by their names.
83 These files should be in appropriate .cfg format.
85 def __init__(self, configFileNames=0):
86 self.getLogger().setLevel(logging.INFO)
87 #it could be None explicitely (if user use multiples setVariable...for standalone)
88 if configFileNames is None:
90 configFileNames = configFileNames or []
91 if len(configFileNames) == 0:
92 raise SalomeContextException("No configuration files given")
94 reserved=['PATH', 'DYLD_FALLBACK_LIBRARY_PATH', 'DYLD_LIBRARY_PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'MANPATH', 'PV_PLUGIN_PATH', 'INCLUDE', 'LIBPATH', 'SALOME_PLUGINS_PATH']
95 for filename in configFileNames:
96 basename, extension = os.path.splitext(filename)
97 if extension == ".cfg":
98 self.__setContextFromConfigFile(filename, reserved)
100 self.getLogger().error("Unrecognized extension for configuration file: %s", filename)
103 def __loadMPI(self, module_name):
104 print("Trying to load MPI module: %s..."%module_name)
106 out, err = subprocess.Popen(["modulecmd", "python", "load", module_name], stdout=subprocess.PIPE).communicate()
107 exec(out) # define specific environment variables
110 print(" ** Failed **")
114 def runSalome(self, args):
116 # Run this module as a script, in order to use appropriate Python interpreter
117 # according to current path (initialized from context files).
118 mpi_module_option = "--with-mpi-module="
119 mpi_module = [x for x in args if x.startswith(mpi_module_option)]
121 mpi_module = mpi_module[0][len(mpi_module_option):]
122 self.__loadMPI(mpi_module)
123 args = [x for x in args if not x.startswith(mpi_module_option)]
125 mpi_module = os.getenv("SALOME_MPI_MODULE_NAME", None)
127 self.__loadMPI(mpi_module)
129 absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
130 env_copy = os.environ.copy()
131 selfBytes= pickle.dumps(self,protocol=0)
132 argsBytes= pickle.dumps(args,protocol=0)
133 proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), selfBytes.decode(), argsBytes.decode()], shell=False, close_fds=True, env=env_copy)
134 out, err = proc.communicate()
135 return out, err, proc.returncode
138 """Append value to PATH environment variable"""
139 def addToPath(self, value):
140 self.addToVariable('PATH', value)
143 """Append value to LD_LIBRARY_PATH environment variable"""
144 def addToLdLibraryPath(self, value):
145 if platform.system() == 'Windows':
146 self.addToVariable('PATH', value)
147 elif platform.system() == 'Darwin':
148 if "LAPACK" in value:
149 self.addToVariable('DYLD_FALLBACK_LIBRARY_PATH', value)
151 self.addToVariable('DYLD_LIBRARY_PATH', value)
153 self.addToVariable('LD_LIBRARY_PATH', value)
156 """Append value to DYLD_LIBRARY_PATH environment variable"""
157 def addToDyldLibraryPath(self, value):
158 self.addToVariable('DYLD_LIBRARY_PATH', value)
161 """Append value to PYTHONPATH environment variable"""
162 def addToPythonPath(self, value):
163 self.addToVariable('PYTHONPATH', value)
166 """Set environment variable to value"""
167 def setVariable(self, name, value, overwrite=False):
168 env = os.getenv(name, '')
169 if env and not overwrite:
170 self.getLogger().error("Environment variable already existing (and not overwritten): %s=%s", name, value)
174 self.getLogger().debug("Overwriting environment variable: %s=%s", name, value)
176 value = os.path.expandvars(value) # expand environment variables
177 self.getLogger().debug("Set environment variable: %s=%s", name, value)
178 os.environ[name] = value
181 """Unset environment variable"""
182 def unsetVariable(self, name):
183 if os.environ.has_key(name):
187 """Append value to environment variable"""
188 def addToVariable(self, name, value, separator=os.pathsep):
192 value = os.path.expandvars(value) # expand environment variables
193 self.getLogger().debug("Add to %s: %s", name, value)
194 env = os.getenv(name, None)
196 os.environ[name] = value
198 os.environ[name] = value + separator + env
201 ###################################
202 # This begins the private section #
203 ###################################
205 def __parseArguments(self, args):
206 if len(args) == 0 or args[0].startswith("-"):
212 availableCommands = {
213 'start' : '_runAppli',
214 'context' : '_setContext',
215 'shell' : '_runSession',
216 'connect' : '_runConsole',
218 'killall' : '_killAll',
219 'test' : '_runTests',
220 'info' : '_showInfo',
223 'coffee' : '_makeCoffee',
227 if not command in list(availableCommands.keys()):
231 return availableCommands[command], options
236 Args consist in a mandatory command followed by optionnal parameters.
237 See usage for details on commands.
239 def _startSalome(self, args):
243 from setenv import add_path
244 absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH')
245 path = os.path.realpath(os.path.join(absoluteAppliPath, "bin", "salome"))
246 add_path(path, "PYTHONPATH")
247 path = os.path.realpath(os.path.join(absoluteAppliPath, "bin", "salome", "appliskel"))
248 add_path(path, "PYTHONPATH")
253 command, options = self.__parseArguments(args)
257 if args and args[0] in ["-h","--help","help"]:
260 # try to default to "start" command
261 command = "_runAppli"
264 res = getattr(self, command)(options) # run appropriate method
265 return res or (None, None)
266 except SystemExit as returncode:
268 self.getLogger().warning("SystemExit %s in method %s.", returncode, command)
271 self.getLogger().error("Unexpected error:")
273 traceback.print_exc()
275 except SalomeContextException as e:
276 self.getLogger().error(e)
280 def __setContextFromConfigFile(self, filename, reserved=None):
284 unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
285 except SalomeContextException as e:
287 self.getLogger().error(msg)
291 for var in unsetVars:
292 self.unsetVariable(var)
295 for reserved in reservedDict:
296 a = [_f for _f in reservedDict[reserved] if _f] # remove empty elements
297 a = [ os.path.realpath(x) for x in a ]
298 reformattedVals = os.pathsep.join(a)
299 if reserved in ["INCLUDE", "LIBPATH"]:
300 self.addToVariable(reserved, reformattedVals, separator=' ')
302 self.addToVariable(reserved, reformattedVals)
305 for key,val in configVars:
306 self.setVariable(key, val, overwrite=True)
309 pythonpath = os.getenv('PYTHONPATH','').split(os.pathsep)
310 pythonpath = [ os.path.realpath(x) for x in pythonpath ]
311 sys.path[:0] = pythonpath
314 def _runAppli(self, args=None):
317 # Initialize SALOME environment
318 sys.argv = ['runSalome'] + args
320 setenv.main(True, exeName="salome start")
323 runSalome.runSalome()
326 def _setContext(self, args=None):
327 salome_context_set = os.getenv("SALOME_CONTEXT_SET")
328 if salome_context_set:
330 print("*** SALOME context has already been set.")
331 print("*** Enter 'exit' (only once!) to leave SALOME context.")
335 os.environ["SALOME_CONTEXT_SET"] = "yes"
337 print("*** SALOME context is now set.")
338 print("*** Enter 'exit' (only once!) to leave SALOME context.")
342 proc = subprocess.Popen(cmd, shell=False, close_fds=True)
343 return proc.communicate()
346 def _runSession(self, args=None):
349 sys.argv = ['runSession'] + args
351 params, args = runSession.configureSession(args, exe="salome shell")
353 sys.argv = ['runSession'] + args
357 return runSession.runSession(params, args)
360 def _runConsole(self, args=None):
363 # Initialize SALOME environment
364 sys.argv = ['runConsole']
369 return runConsole.connect(args)
372 def _kill(self, args=None):
377 print("Port number(s) not provided to command: salome kill <port(s)>")
380 from multiprocessing import Process
381 from killSalomeWithPort import killMyPort
384 with tempfile.NamedTemporaryFile():
385 p = Process(target = killMyPort, args=(port,))
391 def _killAll(self, unused=None):
393 import PortManager # mandatory
394 from multiprocessing import Process
395 from killSalomeWithPort import killMyPort
396 ports = PortManager.getBusyPorts()
401 with tempfile.NamedTemporaryFile():
402 p = Process(target = killMyPort, args=(port,))
406 # :TODO: should be declared obsolete
407 from killSalome import killAllPorts
412 def _runTests(self, args=None):
415 sys.argv = ['runTests']
420 return runTests.runTests(args, exe="salome test")
423 def _showSoftwareVersions(self, softwares=None):
424 config = configparser.SafeConfigParser()
425 absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH')
426 filename = os.path.join(absoluteAppliPath, "sha1_collections.txt")
429 with open(filename) as f:
432 software, version, sha1 = line.split()
433 versions[software.upper()] = version
434 if len(software) > max_len:
435 max_len = len(software)
441 for soft in softwares:
442 if versions.has_key(soft.upper()):
443 print(soft.upper().rjust(max_len), versions[soft.upper()])
446 od = collections.OrderedDict(sorted(versions.items()))
447 for name, version in od.iteritems():
448 print(name.rjust(max_len), versions[name])
451 def _showInfo(self, args=None):
455 usage = "Usage: salome info [options]"
457 Display some information about SALOME.\n
458 Available options are:
459 -p,--ports Show the list of busy ports (running SALOME instances).
460 -s,--softwares [software(s)] Show the list and versions of SALOME softwares.
461 Software names must be separated by blank characters.
462 If no software is given, show version of all softwares.
463 -v,--version Show running SALOME version.
464 -h,--help Show this message.
469 if "-h" in args or "--help" in args:
470 print(usage + epilog)
473 if "-p" in args or "--ports" in args:
475 ports = PortManager.getBusyPorts()
476 print("SALOME instances are running on ports:", ports)
478 print("Last started instance on port %s"%ports[-1])
480 if "-s" in args or "--softwares" in args:
482 index = args.index("-s")
484 index = args.index("--softwares")
486 while indexEnd < len(args) and args[indexEnd][0] != "-":
487 indexEnd = indexEnd + 1
488 self._showSoftwareVersions(softwares=args[index+1:indexEnd])
490 if "-v" in args or "--version" in args:
491 print("Running with python", platform.python_version())
492 self._runAppli(["--version"])
495 def _showDoc(self, args=None):
501 print("Module(s) not provided to command: salome doc <module(s)>")
504 appliPath = os.getenv("ABSOLUTE_APPLI_PATH")
506 raise SalomeContextException("Unable to find application path. Please check that the variable ABSOLUTE_APPLI_PATH is set.")
507 baseDir = os.path.join(appliPath, "share", "doc", "salome")
508 for module in modules:
509 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
510 if not os.path.isfile(docfile):
511 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
512 if not os.path.isfile(docfile):
513 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
514 if os.path.isfile(docfile):
515 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
517 print("Online documentation is not accessible for module:", module)
519 def _usage(self, unused=None):
523 def _makeCoffee(self, unused=None):
526 print(" ___...(-------)-....___")
527 print(" .-\"\" ) ( \"\"-.")
528 print(" .-\'``\'|-._ ) _.-|")
529 print(" / .--.| `\"\"---...........---\"\"` |")
533 print(" `\\ `\\ | |")
534 print(" `\\ `| SALOME |")
535 print(" _/ /\\ 4 EVER /")
536 print(" (__/ \\ <3 /")
537 print(" _..---\"\"` \\ /`\"\"---.._")
538 print(" .-\' \\ / \'-.")
539 print(" : `-.__ __.-\' :")
540 print(" : ) \"\"---...---\"\" ( :")
541 print(" \'._ `\"--...___...--\"` _.\'")
542 print(" \\\"\"--..__ __..--\"\"/")
543 print(" \'._ \"\"\"----.....______.....----\"\"\" _.\'")
544 print(" `\"\"--..,,_____ _____,,..--\"\"`")
545 print(" `\"\"\"----\"\"\"`")
547 print(" SALOME is working for you; what else?")
552 def _getCar(self, unused=None):
553 print(" _____________")
554 print(" ..---:::::::-----------. ::::;;.")
555 print(" .\'\"\"\"\"\"\" ;; \\ \":.")
556 print(" .\'\' ; \\ \"\\__.")
557 print(" .\' ;; ; \\\\\";")
558 print(" .\' ; _____; \\\\/")
559 print(" .\' :; ;\" \\ ___:\'.")
560 print(" .\'--........................... : = ____:\" \\ \\")
561 print(" ..-\"\" \"\"\"\' o\"\"\" ; ; :")
562 print(" .--\"\" .----- ..----... _.- --. ..-\" ; ; ; ;")
563 print(" .\"\"_- \"--\"\"-----\'\"\" _-\" .-\"\" ; ; .-.")
564 print(" .\' .\' SALOME .\" .\" ; ; /. |")
565 print(" /-./\' 4 EVER <3 .\" / _.. ; ; ;;;|")
566 print(" : ;-.______ / _________==. /_ \\ ; ; ;;;;")
567 print(" ; / | \"\"\"\"\"\"\"\"\"\"\".---.\"\"\"\"\"\"\" : /\" \". |; ; _; ;;;")
568 print(" /\"-/ | / / / / ;|; ;-\" | ;\';")
569 print(":- : \"\"\"----______ / / ____. . .\"\'. ;; .-\"..T\" .")
570 print("\'. \" ___ \"\": \'\"\"\"\"\"\"\"\"\"\"\"\"\"\" . ; ; ;; ;.\" .\" \'--\"")
571 print(" \", __ \"\"\" \"\"---... :- - - - - - - - - \' \' ; ; ; ;;\" .\"")
572 print(" /. ; \"\"\"---___ ; ; ; ;|.\"\"")
573 print(" : \": \"\"\"----. .-------. ; ; ; ;:")
574 print(" \\ \'--__ \\ \\ \\ / | ; ;;")
575 print(" \'-.. \"\"\"\"---___ : .______..\\ __/..-\"\"| ; ; ;")
576 print(" \"\"--.. \"\"\"--\" m l s . \". . ;")
577 print(" \"\"------... ..--\"\" \" :")
578 print(" \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \\ /")
581 print(" Drive your simulation properly with SALOME!")
586 # Add the following two methods since logger is not pickable
587 # Ref: http://stackoverflow.com/questions/2999638/how-to-stop-attributes-from-being-pickled-in-python
588 def __getstate__(self):
589 d = dict(self.__dict__)
590 if hasattr(self, '_logger'):
594 def __setstate__(self, d):
595 self.__dict__.update(d) # I *think* this is a safe way to do it
597 # Excluding self._logger from pickle operation imply using the following method to access logger
599 if not hasattr(self, '_logger'):
600 self._logger = logging.getLogger(__name__)
601 #self._logger.setLevel(logging.DEBUG)
602 #self._logger.setLevel(logging.WARNING)
603 self._logger.setLevel(logging.ERROR)
607 if __name__ == "__main__":
608 if len(sys.argv) == 3:
609 context = sys.argv[1]
612 context = pickle.loads(context.encode())
613 args = pickle.loads(args.encode())
615 (out, err) = context._startSalome(args)
617 sys.stdout.write(out)
619 sys.stderr.write(err)