Package PyFoam :: Package Basics :: Module TemplateFile
[hide private]
[frames] | no frames]

Source Code for Module PyFoam.Basics.TemplateFile

  1  #  ICE Revision: $Id$  
  2   
  3  import re,sys 
  4  from math import * 
  5   
  6  from PyFoam.Error import error 
  7   
8 -class TemplateFile:
9 """Works on template files. Does calculations between $$. 10 Lines that start with $$ contain definitions""" 11
12 - def __init__(self,name=None,content=None):
13 """Exactly one of the parameters must be specified 14 @param name: name of the template file. 15 @param content: Content of the template""" 16 if name==None and content==None: 17 error("Either a file name or the content of the template must be specified") 18 if name!=None and content!=None: 19 error("Both: a file name and the content of the template were specified") 20 if content!=None: 21 template=content 22 else: 23 template=open(name).read() 24 25 lines=template.split("\n") 26 self.expressions={} 27 self.template="" 28 for l in lines: 29 if l[:2]!="$$": 30 self.template+=l+"\n" 31 else: 32 tmp=l[2:].split("=") 33 if len(tmp)!=2: 34 error("Each definition must be of the form: <name>=<value>", 35 "The string",l,"is not") 36 self.expressions[tmp[0].strip()]=tmp[1]
37
38 - def writeToFile(self,outfile,vals):
39 """In the template, replaces all the strings between $$ 40 with the evaluation of the expressions and writes the results to a file 41 @param outfile: the resulting output file 42 @param vals: dictionary with the values""" 43 44 output=self.getString(vals) 45 46 open(outfile,"w").write(output)
47
48 - def getString(self,vals):
49 """In the template, replaces all the strings between $$ 50 with the evaluation of the expressions 51 @param vals: dictionary with the values 52 @returns: The string with the replaced expressions""" 53 54 symbols=vals.copy() 55 56 exp=re.compile("\$[^$]*\$") 57 58 for n,e in self.expressions.iteritems(): 59 if vals.has_key(n): 60 error("Key",n,"already existing in",vals) 61 symbols[n]="("+str(e)+")" 62 63 keys=symbols.keys() 64 keys.sort(lambda x,y:cmp(len(y),len(x))) 65 66 input=self.template[:] 67 m=exp.search(input) 68 while m: 69 a,e=m.span() 70 pre=input[0:a] 71 post=input[e:] 72 mid=input[a+1:e-1] 73 74 old="" 75 while old!=mid: 76 old=mid 77 for k in keys: 78 if mid.find(k)>=0: 79 mid=mid.replace(k,str(symbols[k])) 80 break 81 82 try: 83 input=pre+str(eval(mid))+post 84 except ArithmeticError,e: 85 print "Problem evaluating",mid 86 raise e 87 88 m=exp.search(input) 89 90 return input
91
92 - def eval(self,input,vals):
93 """Gets a string, replaces all the strings between $$ 94 with the evaluation of the expressions 95 @param input: the input string 96 @param vals: vector with the values or a dictionary 97 @returns: The string with the replaced expressions""" 98 99 return self.doCalcOnString("$"+input+"$",vals)
100