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
26 from parseConfigFile import convertEnvFileToConfigFile
33 from salomeContextUtils import SalomeContextException
37 Usage: salome [command] [options] [--config=<file,folder,...>]
41 start Start a new SALOME instance.
42 context Initialize SALOME context. Current environment is extended.
43 shell Initialize SALOME context, attached to the last created SALOME
44 instance if any, and executes scripts passed as command arguments.
45 User works in a Shell terminal; SALOME environment is set but
46 application is not started.
47 connect Connect a Python console to the active SALOME instance.
48 kill <port(s)> Terminate SALOME instances running on given ports for current user.
49 Port numbers must be separated by blank characters.
50 killall Terminate *all* SALOME running instances for current user.
51 Do not start a new one.
52 test Run SALOME tests.
53 info Display some information about SALOME.
54 help Show this message.
56 If no command is given, default to start.
60 Use salome <command> --help to show help on command ; available for commands:
61 start, shell, connect, test, info.
63 --config=<file,folder,...>
64 ==========================
65 Initialize SALOME context from a list of context files and/or a list
66 of folders containing context files. The list is comma-separated, whithout
74 The SalomeContext class in an API to configure SALOME context then
75 start SALOME using a single python command.
80 Initialize context from a list of configuration files
81 identified by their names.
82 These files should be in appropriate (new .cfg) format.
83 However you can give old .sh environment files; in this case,
84 the SalomeContext class will try to automatically convert them
85 to .cfg format before setting the context.
87 def __init__(self, configFileNames=0):
88 self.getLogger().setLevel(logging.INFO)
89 #it could be None explicitely (if user use multiples setVariable...for standalone)
90 if configFileNames is None:
92 configFileNames = configFileNames or []
93 if len(configFileNames) == 0:
94 raise SalomeContextException("No configuration files given")
96 reserved=['PATH', 'DYLD_LIBRARY_PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'MANPATH', 'PV_PLUGIN_PATH', 'INCLUDE', 'LIBPATH', 'SALOME_PLUGINS_PATH']
97 for filename in configFileNames:
98 basename, extension = os.path.splitext(filename)
99 if extension == ".cfg":
100 self.__setContextFromConfigFile(filename, reserved)
101 elif extension == ".sh":
102 #new convert procedures, temporary could be use not to be automatically deleted
103 #temp = tempfile.NamedTemporaryFile(suffix='.cfg', delete=False)
104 temp = tempfile.NamedTemporaryFile(suffix='.cfg')
106 convertEnvFileToConfigFile(filename, temp.name, reserved)
107 self.__setContextFromConfigFile(temp.name, reserved)
109 except (ConfigParser.ParsingError, ValueError) as e:
110 self.getLogger().error("Invalid token found when parsing file: %s\n"%(filename))
114 self.getLogger().warning("Unrecognized extension for configuration file: %s", filename)
117 def __loadMPI(self, module_name):
118 print "Trying to load MPI module: %s..."%module_name,
120 out, err = subprocess.Popen(["modulecmd", "python", "load", module_name], stdout=subprocess.PIPE).communicate()
121 exec out # define specific environment variables
124 print " ** Failed **"
128 def runSalome(self, args):
130 # Run this module as a script, in order to use appropriate Python interpreter
131 # according to current path (initialized from context files).
132 mpi_module_option = "--with-mpi-module="
133 mpi_module = [x for x in args if x.startswith(mpi_module_option)]
135 mpi_module = mpi_module[0][len(mpi_module_option):]
136 self.__loadMPI(mpi_module)
137 args = [x for x in args if not x.startswith(mpi_module_option)]
139 mpi_module = os.getenv("SALOME_MPI_MODULE_NAME", None)
141 self.__loadMPI(mpi_module)
143 absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
144 env_copy = os.environ.copy()
145 proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), pickle.dumps(self), pickle.dumps(args)], shell=False, close_fds=True, env=env_copy)
146 out, err = proc.communicate()
147 return out, err, proc.returncode
150 """Append value to PATH environment variable"""
151 def addToPath(self, value):
152 self.addToVariable('PATH', value)
155 """Append value to LD_LIBRARY_PATH environment variable"""
156 def addToLdLibraryPath(self, value):
157 if platform.system() == 'Windows':
158 self.addToVariable('PATH', value)
160 self.addToVariable('LD_LIBRARY_PATH', value)
163 """Append value to DYLD_LIBRARY_PATH environment variable"""
164 def addToDyldLibraryPath(self, value):
165 self.addToVariable('DYLD_LIBRARY_PATH', value)
168 """Append value to PYTHONPATH environment variable"""
169 def addToPythonPath(self, value):
170 self.addToVariable('PYTHONPATH', value)
173 """Set environment variable to value"""
174 def setVariable(self, name, value, overwrite=False):
175 env = os.getenv(name, '')
176 if env and not overwrite:
177 self.getLogger().warning("Environment variable already existing (and not overwritten): %s=%s", name, value)
181 self.getLogger().warning("Overwriting environment variable: %s=%s", name, value)
183 value = os.path.expandvars(value) # expand environment variables
184 self.getLogger().debug("Set environment variable: %s=%s", name, value)
185 os.environ[name] = value
188 """Unset environment variable"""
189 def unsetVariable(self, name):
190 if os.environ.has_key(name):
194 """Append value to environment variable"""
195 def addToVariable(self, name, value, separator=os.pathsep):
199 value = os.path.expandvars(value) # expand environment variables
200 self.getLogger().debug("Add to %s: %s", name, value)
201 env = os.getenv(name, None)
203 os.environ[name] = value
205 os.environ[name] = value + separator + env
208 ###################################
209 # This begins the private section #
210 ###################################
212 def __parseArguments(self, args):
213 if len(args) == 0 or args[0].startswith("-"):
219 availableCommands = {
220 'start' : '_runAppli',
221 'context' : '_setContext',
222 'shell' : '_runSession',
223 'connect' : '_runConsole',
225 'killall' : '_killAll',
226 'test' : '_runTests',
227 'info' : '_showInfo',
229 'coffee' : '_makeCoffee',
233 if not command in availableCommands.keys():
237 return availableCommands[command], options
242 Args consist in a mandatory command followed by optionnal parameters.
243 See usage for details on commands.
245 def _startSalome(self, args):
249 from setenv import add_path
250 absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH')
251 path = os.path.realpath(os.path.join(absoluteAppliPath, "bin", "salome"))
252 add_path(path, "PYTHONPATH")
253 path = os.path.realpath(os.path.join(absoluteAppliPath, "bin", "salome", "appliskel"))
254 add_path(path, "PYTHONPATH")
259 command, options = self.__parseArguments(args)
263 if args and args[0] in ["-h","--help","help"]:
266 # try to default to "start" command
267 command = "_runAppli"
270 res = getattr(self, command)(options) # run appropriate method
271 return res or (None, None)
272 except SystemExit, returncode:
274 self.getLogger().warning("SystemExit %s in method %s.", returncode, command)
276 except StandardError:
277 self.getLogger().error("Unexpected error:")
279 traceback.print_exc()
281 except SalomeContextException, e:
282 self.getLogger().error(e)
286 def __setContextFromConfigFile(self, filename, reserved=None):
290 unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
291 except SalomeContextException, e:
293 file_dir = os.path.dirname(filename)
294 file_base = os.path.basename(filename)
295 base_no_ext, ext = os.path.splitext(file_base)
296 sh_file = os.path.join(file_dir, base_no_ext+'.sh')
297 if ext == ".cfg" and os.path.isfile(sh_file):
298 msg += "Found similar %s file; trying to parse this one instead..."%(base_no_ext+'.sh')
299 temp = tempfile.NamedTemporaryFile(suffix='.cfg')
301 convertEnvFileToConfigFile(sh_file, temp.name, reserved)
302 self.__setContextFromConfigFile(temp.name, reserved)
304 self.getLogger().warning(msg)
307 except (ConfigParser.ParsingError, ValueError) as e:
308 msg += "Invalid token found when parsing file: %s\n"%(sh_file)
309 self.getLogger().error(msg)
313 self.getLogger().error(msg)
317 for var in unsetVars:
318 self.unsetVariable(var)
321 for reserved in reservedDict:
322 a = filter(None, reservedDict[reserved]) # remove empty elements
323 a = [ os.path.realpath(x) for x in a ]
324 reformattedVals = os.pathsep.join(a)
325 if reserved in ["INCLUDE", "LIBPATH"]:
326 self.addToVariable(reserved, reformattedVals, separator=' ')
328 self.addToVariable(reserved, reformattedVals)
331 for key,val in configVars:
332 self.setVariable(key, val, overwrite=True)
335 pythonpath = os.getenv('PYTHONPATH','').split(os.pathsep)
336 pythonpath = [ os.path.realpath(x) for x in pythonpath ]
337 sys.path[:0] = pythonpath
340 def _runAppli(self, args=None):
343 # Initialize SALOME environment
344 sys.argv = ['runSalome'] + args
346 setenv.main(True, exeName="salome start")
349 runSalome.runSalome()
352 def _setContext(self, args=None):
353 salome_context_set = os.getenv("SALOME_CONTEXT_SET")
354 if salome_context_set:
356 print "*** SALOME context has already been set."
357 print "*** Enter 'exit' (only once!) to leave SALOME context."
361 os.environ["SALOME_CONTEXT_SET"] = "yes"
363 print "*** SALOME context is now set."
364 print "*** Enter 'exit' (only once!) to leave SALOME context."
368 proc = subprocess.Popen(cmd, shell=False, close_fds=True)
369 return proc.communicate()
372 def _runSession(self, args=None):
375 sys.argv = ['runSession'] + args
377 params, args = runSession.configureSession(args, exe="salome shell")
379 sys.argv = ['runSession'] + args
383 return runSession.runSession(params, args)
386 def _runConsole(self, args=None):
389 # Initialize SALOME environment
390 sys.argv = ['runConsole']
395 return runConsole.connect(args)
398 def _kill(self, args=None):
403 print "Port number(s) not provided to command: salome kill <port(s)>"
406 from multiprocessing import Process
407 from killSalomeWithPort import killMyPort
410 with tempfile.NamedTemporaryFile():
411 p = Process(target = killMyPort, args=(port,))
417 def _killAll(self, unused=None):
419 import PortManager # mandatory
420 from multiprocessing import Process
421 from killSalomeWithPort import killMyPort
422 ports = PortManager.getBusyPorts()
427 with tempfile.NamedTemporaryFile():
428 p = Process(target = killMyPort, args=(port,))
432 # :TODO: should be declared obsolete
433 from killSalome import killAllPorts
438 def _runTests(self, args=None):
441 sys.argv = ['runTests']
446 return runTests.runTests(args, exe="salome test")
449 def _showInfo(self, args=None):
453 usage = "Usage: salome info [options]"
455 Display some information about SALOME.\n
456 Available options are:
457 -p,--ports Show list of busy ports (running SALOME instances).
458 -v,--version Show running SALOME version.
459 -h,--help Show this message.
464 if "-h" in args or "--help" in args:
468 if "-p" in args or "--ports" in args:
470 ports = PortManager.getBusyPorts()
471 print "SALOME instances are running on ports:", ports
473 print "Last started instance on port %s"%ports[-1]
475 if "-v" in args or "--version" in args:
476 print "Running with python", platform.python_version()
477 self._runAppli(["--version"])
480 def _usage(self, unused=None):
484 def _makeCoffee(self, unused=None):
487 print " ___...(-------)-....___"
488 print " .-\"\" ) ( \"\"-."
489 print " .-\'``\'|-._ ) _.-|"
490 print " / .--.| `\"\"---...........---\"\"` |"
495 print " `\\ `| SALOME |"
496 print " _/ /\\ 4 EVER /"
497 print " (__/ \\ <3 /"
498 print " _..---\"\"` \\ /`\"\"---.._"
499 print " .-\' \\ / \'-."
500 print " : `-.__ __.-\' :"
501 print " : ) \"\"---...---\"\" ( :"
502 print " \'._ `\"--...___...--\"` _.\'"
503 print " \\\"\"--..__ __..--\"\"/"
504 print " \'._ \"\"\"----.....______.....----\"\"\" _.\'"
505 print " `\"\"--..,,_____ _____,,..--\"\"`"
506 print " `\"\"\"----\"\"\"`"
508 print " SALOME is working for you; what else?"
513 def _getCar(self, unused=None):
514 print " _____________"
515 print " ..---:::::::-----------. ::::;;."
516 print " .\'\"\"\"\"\"\" ;; \\ \":."
517 print " .\'\' ; \\ \"\\__."
518 print " .\' ;; ; \\\\\";"
519 print " .\' ; _____; \\\\/"
520 print " .\' :; ;\" \\ ___:\'."
521 print " .\'--........................... : = ____:\" \\ \\"
522 print " ..-\"\" \"\"\"\' o\"\"\" ; ; :"
523 print " .--\"\" .----- ..----... _.- --. ..-\" ; ; ; ;"
524 print " .\"\"_- \"--\"\"-----\'\"\" _-\" .-\"\" ; ; .-."
525 print " .\' .\' SALOME .\" .\" ; ; /. |"
526 print " /-./\' 4 EVER <3 .\" / _.. ; ; ;;;|"
527 print " : ;-.______ / _________==. /_ \\ ; ; ;;;;"
528 print " ; / | \"\"\"\"\"\"\"\"\"\"\".---.\"\"\"\"\"\"\" : /\" \". |; ; _; ;;;"
529 print " /\"-/ | / / / / ;|; ;-\" | ;\';"
530 print ":- : \"\"\"----______ / / ____. . .\"\'. ;; .-\"..T\" ."
531 print "\'. \" ___ \"\": \'\"\"\"\"\"\"\"\"\"\"\"\"\"\" . ; ; ;; ;.\" .\" \'--\""
532 print " \", __ \"\"\" \"\"---... :- - - - - - - - - \' \' ; ; ; ;;\" .\""
533 print " /. ; \"\"\"---___ ; ; ; ;|.\"\""
534 print " : \": \"\"\"----. .-------. ; ; ; ;:"
535 print " \\ \'--__ \\ \\ \\ / | ; ;;"
536 print " \'-.. \"\"\"\"---___ : .______..\\ __/..-\"\"| ; ; ;"
537 print " \"\"--.. \"\"\"--\" m l s . \". . ;"
538 print " \"\"------... ..--\"\" \" :"
539 print " \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \\ /"
542 print " Drive your simulation properly with SALOME!"
547 # Add the following two methods since logger is not pickable
548 # Ref: http://stackoverflow.com/questions/2999638/how-to-stop-attributes-from-being-pickled-in-python
549 def __getstate__(self):
550 d = dict(self.__dict__)
551 if hasattr(self, '_logger'):
555 def __setstate__(self, d):
556 self.__dict__.update(d) # I *think* this is a safe way to do it
558 # Excluding self._logger from pickle operation imply using the following method to access logger
560 if not hasattr(self, '_logger'):
561 self._logger = logging.getLogger(__name__)
562 #self._logger.setLevel(logging.DEBUG)
563 #self._logger.setLevel(logging.WARNING)
564 self._logger.setLevel(logging.ERROR)
568 if __name__ == "__main__":
569 if len(sys.argv) == 3:
570 context = pickle.loads(sys.argv[1])
571 args = pickle.loads(sys.argv[2])
573 (out, err) = context._startSalome(args)
575 sys.stdout.write(out)
577 sys.stderr.write(err)