3 # Copyright (C) 2013-2016 CEA/DEN, EDF R&D, OPEN CASCADE
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, or (at your option) any later version.
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
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
31 Define a specific exception class to manage exceptions related to SalomeContext
33 class SalomeContextException(Exception):
34 """Report error messages to the user interface of SalomeContext."""
37 def __listDirectory(path):
39 for root, dirs, files in os.walk(path):
40 cfgFiles = glob.glob(os.path.join(root,'*.cfg'))
43 shFiles = glob.glob(os.path.join(root,'*.sh'))
45 no_ext = os.path.splitext(f)[0]
46 if not os.path.isfile(no_ext+".cfg"):
52 def __getConfigFileNamesDefault():
53 absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
54 if not absoluteAppliPath:
57 envdDir = absoluteAppliPath + '/env.d'
58 if not os.path.isdir(envdDir):
61 return __listDirectory(envdDir)
64 def __getEnvironmentFileNames(args, optionPrefix, checkExistence):
65 # special case: extra configuration/environment files are provided by user
66 # Search for command-line argument(s) <optionPrefix>=file1,file2,..., filen
67 # Search for command-line argument(s) <optionPrefix>=dir1,dir2,..., dirn
68 configArgs = [ str(x) for x in args if str(x).startswith(optionPrefix) ]
70 args = [ x for x in args if not x.startswith(optionPrefix) ]
71 allLists = [ x.replace(optionPrefix, '') for x in configArgs ]
75 for currentList in allLists:
76 elements = currentList.split(',')
78 elt = os.path.realpath(os.path.expanduser(elt))
79 if os.path.isdir(elt):
80 configFileNames += __listDirectory(elt)
82 if checkExistence and not os.path.isfile(elt):
85 configFileNames += [elt]
87 return configFileNames, args, unexisting
90 def getConfigFileNames(args, checkExistence=False):
91 configOptionPrefix = "--config="
92 configArgs = [ str(x) for x in args if str(x).startswith(configOptionPrefix) ]
93 if len(configArgs) == 0:
94 configFileNames, unexist = __getConfigFileNamesDefault(), []
96 # get configuration filenames
97 configFileNames, args, unexist = __getEnvironmentFileNames(args, configOptionPrefix, checkExistence)
99 return configFileNames, args, unexist
102 def __getScriptPath(scriptName, searchPathList):
103 scriptName = os.path.expanduser(scriptName)
104 if os.path.isabs(scriptName):
107 if searchPathList is None or len(searchPathList) == 0:
110 for path in searchPathList:
111 fullName = os.path.join(path, scriptName)
112 if os.path.isfile(fullName) or os.path.isfile(fullName+".py"):
119 # script: the command to be run, e.g. python <script.py>
120 # args: its input parameters
121 # out: its output parameters
122 def __init__(self, script=None, args=None, out=None):
128 msg = "\n# Script: %s\n"%self.script
129 msg += " * Input: %s\n"%self.args
130 msg += " * Output: %s\n"%self.out
134 class ScriptAndArgsObjectEncoder(json.JSONEncoder):
135 def default(self, obj):
136 if isinstance(obj, ScriptAndArgs):
137 # to be easily parsed in GUI module (SalomeApp_Application)
138 # Do not export output arguments
139 return {obj.script:obj.args or []}
141 return json.JSONEncoder.default(self, obj)
144 def getShortAndExtraArgs(args=None):
148 pos = args.index("--") # raise a ValueError if not found
149 short_args = args[:pos]
150 extra_args = args[pos:] # include "--"
156 return short_args, extra_args
159 # Return an array of ScriptAndArgs objects
160 def getScriptsAndArgs(args=None, searchPathList=None):
163 short_args, extra_args = getShortAndExtraArgs(args)
166 if searchPathList is None:
167 searchPathList = sys.path
169 # Syntax of args: script.py [args:a1,a2=val,an] ... script.py [args:a1,a2=val,an]
178 for i in range(len(args)):
179 elt = os.path.expanduser(args[i])
180 isDriver = (elt == "driver") # special case for YACS scheme execution
182 if elt.startswith(argsPrefix):
183 if not currentKey or callPython:
184 raise SalomeContextException("args list must follow corresponding script file in command line.")
185 elt = elt.replace(argsPrefix, '')
186 # Special process if some items of 'args:' list are themselves lists
187 # Note that an item can be a list, but not a list of lists...
188 # So we can have something like this:
189 # myscript.py args:['file1','file2'],val1,"done",[1,2,3],[True,False],"ok"
190 # 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'
191 # We have to split elt to obtain: ['[file1,file2]','val1','done','[1,2,3]','[True,False]','ok']
192 contains_list = re.findall('(\[[^\]]*\])', elt)
196 # x is ['[file1', 'file2]', 'val1', 'done', '[1', '2', '3]', '[True', 'False]', 'ok']
197 list_begin_indices = [i for i in xrange(len(x)) if x[i].startswith('[')] # [0, 4, 7]
198 list_end_indices = [i for i in xrange(len(x)) if x[i].endswith(']')] # [1, 6, 8]
200 for lbeg, lend in zip(list_begin_indices,list_end_indices): # [(0, 1), (4, 6), (7, 8)]
202 extracted_args += x[start:lbeg]
204 extracted_args += [','.join(x[lbeg:lend+1])]
208 extracted_args += x[start:len(x)]
210 scriptArgs[len(scriptArgs)-1].args = extracted_args
212 else: # a single split is enough
213 scriptArgs[len(scriptArgs)-1].args = [os.path.expanduser(x) for x in elt.split(",")]
218 elif elt.startswith(outPrefix):
219 if (not currentKey and not afterArgs) or callPython:
220 raise SalomeContextException("out list must follow both corresponding script file and its args in command line.")
221 elt = elt.replace(outPrefix, '')
222 scriptArgs[len(scriptArgs)-1].out = [os.path.expanduser(x) for x in elt.split(",")]
226 elif elt.startswith("python"):
230 if not os.path.isfile(elt) and not os.path.isfile(elt+".py"):
231 eltInSearchPath = __getScriptPath(elt, searchPathList)
232 if eltInSearchPath is None or (not os.path.isfile(eltInSearchPath) and not os.path.isfile(eltInSearchPath+".py")):
233 if elt[-3:] == ".py":
234 raise SalomeContextException("Script not found: %s"%elt)
235 scriptArgs.append(ScriptAndArgs(script=elt))
237 elt = eltInSearchPath
239 if elt[-4:] != ".hdf":
240 if elt[-3:] == ".py" or isDriver:
241 currentScript = os.path.abspath(elt)
242 elif os.path.isfile(elt+".py"):
243 currentScript = os.path.abspath(elt+".py")
245 currentScript = os.path.abspath(elt) # python script not necessary has .py extension
248 if currentScript and callPython:
249 currentKey = "@PYTHONBIN@ "+currentScript
250 scriptArgs.append(ScriptAndArgs(script=currentKey))
254 currentKey = currentScript
255 scriptArgs.append(ScriptAndArgs(script=currentKey))
257 elif not os.access(currentScript, os.X_OK):
258 currentKey = "@PYTHONBIN@ "+currentScript
259 scriptArgs.append(ScriptAndArgs(script=currentKey))
263 fn = open(currentScript)
264 for i in xrange(10): # read only 10 first lines
266 if re.search("#!.*python"):
273 if not ispython and currentScript[-3:] == ".py":
274 currentKey = "@PYTHONBIN@ "+currentScript
276 currentKey = currentScript
278 scriptArgs.append(ScriptAndArgs(script=currentKey))
279 # CLOSE elif currentScript
283 if len(extra_args) > 1: # syntax: -- program [options] [arguments]
284 command = extra_args[1]
285 command_args = extra_args[2:]
286 scriptArgs.append(ScriptAndArgs(script=command, args=command_args))
292 # Formatting scripts and args as a Bash-like command-line:
293 # script1.py [args] ; script2.py [args] ; ...
294 # scriptArgs is a list of ScriptAndArgs objects; their output parameters are omitted
295 def formatScriptsAndArgs(scriptArgs=None):
296 if scriptArgs is None:
299 for sa_obj in scriptArgs:
302 cmd = " ".join([cmd]+sa_obj.args)
306 if sys.platform == "win32":
308 command = sep.join(["%s"%x for x in commands])
312 # Ensure OMNIORB_USER_PATH is defined. This variable refers to a folder in which
313 # SALOME will write omniOrb configuration files.
314 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
315 # an exception is raised if check fails. It allows users for choosing a specific folder.
316 # Else the function sets OMNIORB_USER_PATH this way:
317 # - If APPLI environment variable is set, OMNIORB_USER_PATH is set to ${APPLI}/USERS.
318 # The function does not check USERS folder existence or write access. This folder
319 # must exist ; this is the case if SALOME virtual application has been created using
320 # appli_gen.py script.
321 # - Else OMNIORB_USER_PATH is set to user home directory.
322 def setOmniOrbUserPath():
323 omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
325 if not os.access(omniorbUserPath, os.W_OK):
326 raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
329 homePath = os.path.realpath(os.path.expanduser('~'))
330 #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
331 defaultOmniorbUserPath = homePath
332 if os.getenv("APPLI"):
333 defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
335 os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
339 return socket.gethostname().split('.')[0]