Package PyFoam :: Module FoamInformation
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.FoamInformation

  1  #  ICE Revision: $Id$ 
  2  """Getting Information about the Foam-Installation (like the installation directory)""" 
  3   
  4  from os import environ,path,listdir 
  5  import sys 
  6   
  7  if sys.version_info<(2,6): 
  8      from popen2 import popen4 
  9  else: 
 10      from subprocess import Popen,PIPE,STDOUT 
 11   
 12  import re 
 13   
 14  from PyFoam.Error import error,warning 
 15   
 16  from PyFoam import configuration as config 
 17   
18 -def getPathFromEnviron(name):
19 """Gets a path from an environment variable 20 @return: the path 21 @rtype: string 22 @param name: the name of the environment variable""" 23 24 tmp="" 25 if name in environ: 26 tmp=path.normpath(environ[name]) 27 28 return tmp
29
30 -def foamTutorials():
31 """@return: directory in which the tutorials reside""" 32 33 return getPathFromEnviron("FOAM_TUTORIALS")
34
35 -def foamMPI():
36 """@return: the used MPI-Implementation""" 37 if "WM_MPLIB" not in environ: 38 return () 39 else: 40 vStr=environ["WM_MPLIB"] 41 return vStr
42
43 -def foamVersionString(useConfigurationIfNoInstallation=False):
44 """@return: string for the Foam-version as found 45 in $WM_PROJECT_VERSION""" 46 47 if "WM_PROJECT_VERSION" not in environ and not useConfigurationIfNoInstallation: 48 return "" 49 else: 50 if "WM_PROJECT_VERSION" in environ: 51 vStr=environ["WM_PROJECT_VERSION"] 52 else: 53 vStr="" 54 55 if vStr=="" and useConfigurationIfNoInstallation: 56 vStr=config().get("OpenFOAM","Version") 57 58 return vStr
59
60 -class VersionTuple(tuple):
61 """Wrapper around the regular tuple that is printed in a way that 62 can be parsed as a tuple in a OF-dictionary 63 64 """ 65 66 # Python3 doesn't like this. But it was only here out of courtesy 67 # def __init__(self,data): 68 # tuple.__init__(self,data) 69
70 - def __str__(self):
71 return ".".join([str(e) for e in self])
72
73 -def foamVersion(useConfigurationIfNoInstallation=False):
74 """@return: tuple that represents the Foam-version as found 75 in $WM_PROJECT_VERSION""" 76 77 vStr=foamVersionString(useConfigurationIfNoInstallation=useConfigurationIfNoInstallation) 78 79 if vStr=="": 80 return () 81 else: 82 res=[] 83 84 for el in vStr.split("."): 85 for e in el.split("-"): 86 try: 87 res.append(int(e)) 88 except: 89 res.append(e) 90 91 return VersionTuple(res)
92
93 -def foamVersionNumber(useConfigurationIfNoInstallation=False):
94 """@return: tuple that represents the Foam-Version-Number (without 95 strings""" 96 97 ver=foamVersion(useConfigurationIfNoInstallation=useConfigurationIfNoInstallation) 98 99 nr=[] 100 101 for e in ver: 102 if type(e)==int: 103 nr.append(e) 104 else: 105 break 106 107 return VersionTuple(nr)
108
109 -def oldAppConvention():
110 """Returns true if the version of OpenFOAM is older than 1.5 and 111 it therefor uses the 'old' convention to call utilities ("dot, case") 112 """ 113 return foamVersionNumber()<(1,5)
114
115 -def oldTutorialStructure():
116 """Returns true if the version of OpenFOAM is older than 1.6 and 117 it therefor uses the 'old' (flat) structure for the tutorials 118 """ 119 return foamVersionNumber()<(1,6)
120
121 -def installationPath():
122 """Path to the installation""" 123 return path.abspath(environ["WM_PROJECT_DIR"])
124
125 -def findInstalledVersions(basedir,valid,forkName="openfoam"):
126 versions={} 127 128 basedir=path.abspath(basedir) 129 130 try: 131 candidates=listdir(basedir) 132 except OSError: 133 return versions 134 135 for f in candidates: 136 m=valid.match(f) 137 if m: 138 dname=path.join(basedir,f) 139 if path.isdir(dname): 140 name=m.groups(1)[0] 141 dotDir=path.join(dname,".OpenFOAM-"+name) 142 etcDir=path.join(dname,"etc") 143 if path.isdir(etcDir) and path.exists(path.join(etcDir,"bashrc")): 144 versions[(forkName,m.groups(1)[0])]=dname 145 elif path.isdir(dotDir) and path.exists(path.join(dotDir,"bashrc")): 146 versions[(forkName,m.groups(1)[0])]=dname 147 148 return versions
149 150 __foamInstallations=None 151
152 -def findInstallationDir(newVersion):
153 installed=foamInstalledVersions() 154 found=[] 155 156 for fork,version in installed.keys(): 157 if newVersion==version: 158 found.append((fork,version)) 159 elif newVersion==(fork+"-"+version): 160 found.append((fork,version)) 161 162 if len(found)==0: 163 error("Can't find basedir for OpenFOAM-version",newVersion,"in", 164 ", ".join([ a[0]+"-"+a[1] for a in installed.keys() ])) 165 elif len(found)==1: 166 return found[0][0],found[0][1],installed[found[0]] 167 else: 168 error("Requested version:",newVersion,"Matches found:", 169 ", ".join([ a[0]+"-"+a[1] for a in found ]))
170
171 -def foamInstalledVersions():
172 """@return: A list with the installed versions of OpenFOAM""" 173 global __foamInstallations 174 175 if __foamInstallations: 176 return __foamInstallations 177 178 __foamInstallations={} 179 180 "^OpenFOAM-([0-9]\.[0-9].*)$","^openfoam([0-9]+)$" 181 forks=config().getList("OpenFOAM","Forks") 182 183 for fork in forks: 184 currentFork=foamFork() 185 186 if "WM_PROJECT_INST_DIR" in environ and currentFork==fork: 187 basedir=environ["WM_PROJECT_INST_DIR"] 188 else: 189 basedir=path.expanduser(config().get("OpenFOAM","Installation-"+fork)) 190 191 if not path.exists(basedir) or not path.isdir(basedir): 192 warning("Basedir",basedir,"for fork",fork,"does not exist or is not a directory") 193 continue 194 195 for bdir in [basedir]+config().getList("OpenFOAM","AdditionalInstallation"): 196 for val in [re.compile(s) for s in config().getList("OpenFOAM","DirPatterns-"+fork)]: 197 __foamInstallations.update(findInstalledVersions(bdir,val,fork)) 198 199 return __foamInstallations
200
201 -def foamFork():
202 """The currently used fork of OpenFOAM/Foam""" 203 try: 204 return environ["WM_FORK"] 205 except KeyError: 206 return "openfoam"
207
208 -def changeFoamVersion(new, 209 force64=False, 210 force32=False, 211 compileOption=None, 212 foamCompiler=None, 213 wmCompiler=None):
214 """Changes the used FoamVersion. Only valid during the runtime of 215 the interpreter (the script or the Python session) 216 @param new: The new Version 217 @param force64: Forces the 64-bit-version to be chosen 218 @param force32: Forces the 32-bit-version to be chosen 219 @param compileOption: Forces Debug or Opt 220 @param wmCompiler: Force new value for WM_COMPILER 221 @param foamCompiler: Force system or OpenFOAM-Compiler""" 222 223 newFork,newVersion,basedir=findInstallationDir(new) 224 225 old=None 226 oldFork=foamFork() 227 if "WM_PROJECT_VERSION" in environ: 228 old=environ["WM_PROJECT_VERSION"] 229 if newVersion==old and newFork==oldFork: 230 warning(old+"-"+foamFork(),"is already being used") 231 else: 232 warning("No OpenFOAM-Version installed") 233 234 if path.exists(path.join(basedir,"etc")): 235 script=path.join(basedir,"etc","bashrc") 236 else: 237 script=path.join(basedir,".OpenFOAM-"+new,"bashrc") 238 239 forceArchOption=None 240 if force64: 241 forceArchOption="64" 242 elif force32: 243 forceArchOption="32" 244 245 injectVariables(script, 246 forceArchOption=forceArchOption, 247 compileOption=compileOption, 248 foamCompiler=foamCompiler, 249 wmCompiler=wmCompiler) 250 251 try: 252 if old==environ["WM_PROJECT_VERSION"] and oldFork==foamFork(): 253 warning("Problem while changing to version",new,"old version still used:",foamFork()+"-"+environ["WM_PROJECT_VERSION"]) 254 except KeyError: 255 pass
256
257 -def injectVariables(script, 258 forceArchOption=None, 259 compileOption=None, 260 foamCompiler=None, 261 wmCompiler=None):
262 """Executes a script in a subshell and changes the current 263 environment with the enivironment after the execution 264 @param script: the script that is executed 265 @param forceArchOption: To which architecture Option should be forced 266 @param compileOption: to which value the WM_COMPILE_OPTION should be forced 267 @param wmCompiler: Force new value for WM_COMPILER 268 @param foamCompiler: Force system or OpenFOAM-Compiler""" 269 270 # Certan bashrc-s fail if these are set 271 for v in ["FOAM_INST_DIR", 272 "WM_THIRD_PARTY_DIR", 273 "WM_PROJECT_USER_DIR", 274 "OPAL_PREFIX"]: 275 try: 276 del environ[v] 277 except KeyError: 278 pass 279 280 if not path.exists(script): 281 error("Can not execute",script,"it does not exist") 282 283 try: 284 if "SHELL" in environ: 285 shell=environ["SHELL"] 286 287 if(path.basename(shell).find("python")==0): 288 # this assumes that the 'shell' is a PyFoam-Script on a cluster 289 shell=config().get("Paths","bash") 290 environ["SHELL"]=shell 291 292 allowedShells = [ "bash", "zsh"] 293 if not path.basename(shell) in allowedShells: 294 error("Currently only implemented for the shells",allowedShells,", not for",shell) 295 296 cmd="" 297 postCmd="" 298 if forceArchOption!=None: 299 cmd+="export WM_ARCH_OPTION="+forceArchOption+"; " 300 postCmd+=" WM_ARCH_OPTION="+forceArchOption 301 if compileOption!=None: 302 cmd+="export WM_COMPILE_OPTION="+compileOption+"; " 303 postCmd+=" WM_COMPILE_OPTION="+compileOption 304 if foamCompiler!=None: 305 cmd+="export foamCompiler="+foamCompiler+"; " 306 postCmd+=" foamCompiler="+foamCompiler 307 if wmCompiler!=None: 308 cmd+="export WM_COMPILER="+wmCompiler+"; " 309 postCmd+=" WM_COMPILER="+wmCompiler 310 cmd+=". "+script+postCmd+'; echo "Starting The Dump Of Variables"; export' 311 except KeyError: 312 # Instead of 'KeyError as name'. This is compatible with 2.4-3.2 313 # http://docs.pythonsprints.com/python3_porting/py-porting.html#handling-exceptions 314 name = sys.exc_info()[1] 315 error("Can't do it, because shell variable",name,"is undefined") 316 317 if sys.version_info<(2,6): 318 raus,rein = popen4(cmd) 319 else: 320 p = Popen(cmd, shell=True, 321 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) 322 (rein,raus)=(p.stdin,p.stdout) 323 324 lines=[l.strip().decode() for l in raus.readlines()] 325 rein.close() 326 raus.close() 327 328 # clumsy but avoids more complicated expressions 329 exp=re.compile('export (.+)="(.*)"$') 330 exp2=re.compile("export (.+)='(.*)'$") 331 332 cnt=0 333 334 for l in lines: 335 m=exp.match(str(l)) 336 if not m: 337 m=exp2.match(str(l)) 338 if m: 339 cnt+=1 340 environ[m.groups()[0]]=m.groups()[1]
341 342 # Should work with Python3 and Python2 343