1 # Copyright (C) 2013-2024 CEA, EDF, 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
29 Define a specific exception class to manage exceptions related to SalomeContext
31 class SalomeContextException(Exception):
32 """Report error messages to the user interface of SalomeContext."""
35 def __listDirectory(path):
37 for root, dirs, files in os.walk(path):
38 cfgFiles = glob.glob(os.path.join(root,'*.cfg'))
44 def __getConfigFileNamesDefault():
45 absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
46 if not absoluteAppliPath:
49 envdDir = absoluteAppliPath + '/env.d'
50 if not os.path.isdir(envdDir):
53 return __listDirectory(envdDir)
56 def __getEnvironmentFileNames(args, optionPrefix, checkExistence):
57 # special case: extra configuration/environment files are provided by user
58 # Search for command-line argument(s) <optionPrefix>=file1,file2,..., filen
59 # Search for command-line argument(s) <optionPrefix>=dir1,dir2,..., dirn
60 configArgs = [ str(x) for x in args if str(x).startswith(optionPrefix) ]
62 args = [ x for x in args if not x.startswith(optionPrefix) ]
63 allLists = [ x.replace(optionPrefix, '') for x in configArgs ]
67 for currentList in allLists:
68 elements = currentList.split(',')
70 elt = os.path.realpath(os.path.expanduser(elt))
71 if os.path.isdir(elt):
72 configFileNames += __listDirectory(elt)
74 if checkExistence and not os.path.isfile(elt):
77 configFileNames += [elt]
79 return configFileNames, args, unexisting
82 def getConfigFileNames(args, checkExistence=False):
83 configOptionPrefix = "--config="
84 configArgs = [ str(x) for x in args if str(x).startswith(configOptionPrefix) ]
85 if len(configArgs) == 0:
86 configFileNames, unexist = __getConfigFileNamesDefault(), []
88 # get configuration filenames
89 configFileNames, args, unexist = __getEnvironmentFileNames(args, configOptionPrefix, checkExistence)
91 return configFileNames, args, unexist
94 def __getScriptPath(scriptName, searchPathList):
95 scriptName = os.path.expanduser(scriptName)
96 if os.path.isabs(scriptName):
99 if searchPathList is None or len(searchPathList) == 0:
102 for path in searchPathList:
103 fullName = os.path.join(path, scriptName)
104 if os.path.isfile(fullName) or os.path.isfile(fullName+".py"):
111 # script: the command to be run, e.g. python <script.py>
112 # args: its input parameters
113 # out: its output parameters
114 def __init__(self, script=None, args=None, out=None):
120 msg = "\n# Script: %s\n"%self.script
121 msg += " * Input: %s\n"%self.args
122 msg += " * Output: %s\n"%self.out
126 class ScriptAndArgsObjectEncoder(json.JSONEncoder):
127 def default(self, obj):
128 if isinstance(obj, ScriptAndArgs):
129 # to be easily parsed in GUI module (SalomeApp_Application)
130 # Do not export output arguments
131 return {obj.script:obj.args or []}
133 return json.JSONEncoder.default(self, obj)
136 def getShortAndExtraArgs(args=None):
140 pos = args.index("--") # raise a ValueError if not found
141 short_args = args[:pos]
142 extra_args = args[pos:] # include "--"
148 return short_args, extra_args
151 # Return an array of ScriptAndArgs objects
152 def getScriptsAndArgs(args=None, searchPathList=None):
155 short_args, extra_args = getShortAndExtraArgs(args)
158 if searchPathList is None:
159 searchPathList = sys.path
161 # Syntax of args: script.py [args:a1,a2=val,an] ... script.py [args:a1,a2=val,an]
170 for i in range(len(args)):
171 elt = os.path.expanduser(args[i])
172 isDriver = (elt == "driver") # special case for YACS scheme execution
174 if elt.startswith(argsPrefix):
175 if not currentKey or callPython:
176 raise SalomeContextException("args list must follow corresponding script file in command line.")
177 elt = elt.replace(argsPrefix, '')
178 # Special process if some items of 'args:' list are themselves lists
179 # Note that an item can be a list, but not a list of lists...
180 # So we can have something like this:
181 # myscript.py args:['file1','file2'],val1,"done",[1,2,3],[True,False],"ok"
182 # With such a call, an elt variable contains the string representing ['file1','file2'],val1,"done",[1,2,3],[True,False],"ok" that is '[file1,file2],val1,done,[1,2,3],[True,False],ok'
183 # We have to split elt to obtain: ['[file1,file2]','val1','done','[1,2,3]','[True,False]','ok']
184 contains_list = re.findall('(\[[^\]]*\])', elt)
188 # x is ['[file1', 'file2]', 'val1', 'done', '[1', '2', '3]', '[True', 'False]', 'ok']
189 list_begin_indices = [i for i in range(len(x)) if x[i].startswith('[')] # [0, 4, 7]
190 list_end_indices = [i for i in range(len(x)) if x[i].endswith(']')] # [1, 6, 8]
192 for lbeg, lend in zip(list_begin_indices,list_end_indices): # [(0, 1), (4, 6), (7, 8)]
194 extracted_args += x[start:lbeg]
196 extracted_args += [','.join(x[lbeg:lend+1])]
200 extracted_args += x[start:len(x)]
202 scriptArgs[len(scriptArgs)-1].args = extracted_args
204 else: # a single split is enough
205 scriptArgs[len(scriptArgs)-1].args = [os.path.expanduser(x) for x in elt.split(",")]
210 elif elt.startswith(outPrefix):
211 if (not currentKey and not afterArgs) or callPython:
212 raise SalomeContextException("out list must follow both corresponding script file and its args in command line.")
213 elt = elt.replace(outPrefix, '')
214 scriptArgs[len(scriptArgs)-1].out = [os.path.expanduser(x) for x in elt.split(",")]
218 elif elt.startswith("python"):
222 file_extension = os.path.splitext(elt)[-1]
223 if not os.path.isfile(elt) and not os.path.isfile(elt+".py"):
224 eltInSearchPath = __getScriptPath(elt, searchPathList)
225 if eltInSearchPath is None or (not os.path.isfile(eltInSearchPath) and not os.path.isfile(eltInSearchPath+".py")):
226 if file_extension == ".py":
227 raise SalomeContextException("Script not found: %s"%elt)
228 scriptArgs.append(ScriptAndArgs(script=elt))
230 elt = eltInSearchPath
232 if file_extension != ".hdf":
233 if file_extension == ".py" or isDriver:
234 currentScript = os.path.abspath(elt)
235 elif os.path.isfile(elt+".py"):
236 currentScript = os.path.abspath(elt+".py")
238 currentScript = os.path.abspath(elt) # python script not necessary has .py extension
241 if currentScript and callPython:
242 currentKey = "@PYTHONBIN@ "+currentScript
243 scriptArgs.append(ScriptAndArgs(script=currentKey))
246 script_extension = os.path.splitext(currentScript)[-1]
248 currentKey = currentScript
249 scriptArgs.append(ScriptAndArgs(script=currentKey))
251 elif not os.access(currentScript, os.X_OK):
252 currentKey = "@PYTHONBIN@ "+currentScript
253 scriptArgs.append(ScriptAndArgs(script=currentKey))
257 fn = open(currentScript)
258 for i in range(10): # read only 10 first lines
260 if re.search("#!.*python"):
268 if not ispython and script_extension == ".py":
269 currentKey = "@PYTHONBIN@ "+currentScript
271 currentKey = currentScript
273 scriptArgs.append(ScriptAndArgs(script=currentKey))
274 # CLOSE elif currentScript
278 if len(extra_args) > 1: # syntax: -- program [options] [arguments]
279 command = extra_args[1]
280 command_args = extra_args[2:]
281 scriptArgs.append(ScriptAndArgs(script=command, args=command_args))
287 # Formatting scripts and args as a Bash-like command-line:
288 # script1.py [args] ; script2.py [args] ; ...
289 # scriptArgs is a list of ScriptAndArgs objects; their output parameters are omitted
290 def formatScriptsAndArgs(scriptArgs=None, escapeSpaces=False):
291 if scriptArgs is None:
294 for sa_obj in scriptArgs:
296 if escapeSpaces and cmd:
297 if sys.platform == "win32":
298 cmd = cmd.replace(' ', ' "', 1)
301 cmd = cmd.replace(' ', '\ ').replace('\ ', ' ', 1)
303 cmd = " ".join([cmd]+sa_obj.args)
307 if sys.platform == "win32":
309 command = sep.join(["%s"%x for x in commands])
313 # Ensure OMNIORB_USER_PATH is defined. This variable refers to a folder in which
314 # SALOME will write omniOrb configuration files.
315 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
316 # an exception is raised if check fails. It allows users for choosing a specific folder.
317 # Else the function sets OMNIORB_USER_PATH this way:
318 # - If APPLI environment variable is set, and if ${APPLI}/USERS points at an existing
319 # folder with write access, then OMNIORB_USER_PATH is set to ${APPLI}/USERS.
320 # This is the case if SALOME virtual application has been created using
321 # appli_gen.py script.
322 # - Else OMNIORB_USER_PATH is set to user home directory.
323 def setOmniOrbUserPath():
324 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
326 if not os.access(omniorbUserPath, os.W_OK):
327 raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
330 # Must be in /tmp (or equivalent) to handle application concurrency
333 temp = tempfile.NamedTemporaryFile()
334 temp_dir = os.path.dirname(temp.name)
336 if not os.access(temp_dir, os.W_OK):
337 raise Exception("Unable to get write access to directory: %s"%temp_dir)
338 os.environ["OMNIORB_USER_PATH"] = temp_dir
340 homePath = os.path.realpath(os.path.expanduser('~'))
341 #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
342 defaultOmniorbUserPath = homePath
343 if os.getenv("APPLI"):
344 appli_users_path=os.path.join(homePath, os.getenv("APPLI"), "USERS")
345 if os.access(appli_users_path, os.W_OK):
346 defaultOmniorbUserPath = appli_users_path
348 os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
352 return socket.gethostname().split('.')[0]