1
2
3 import re,sys
4 from math import *
5
6 from PyFoam.Error import error
7
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
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
49 """In the template, replaces all the strings between $$
50 with the evaluation of the expressions
51 @param input: the input string
52 @param vals: dictionary with the values
53 @returns: The string with the replaced expressions"""
54
55 symbols=vals.copy()
56
57 exp=re.compile("\$[^$]*\$")
58
59 for n,e in self.expressions.iteritems():
60 if vals.has_key(n):
61 error("Key",n,"already existing in",vals)
62 symbols[n]="("+str(e)+")"
63
64 keys=symbols.keys()
65 keys.sort(lambda x,y:cmp(len(y),len(x)))
66
67 input=self.template[:]
68 m=exp.search(input)
69 while m:
70 a,e=m.span()
71 pre=input[0:a]
72 post=input[e:]
73 mid=input[a+1:e-1]
74
75 old=""
76 while old!=mid:
77 old=mid
78 for k in keys:
79 if mid.find(k)>=0:
80 mid=mid.replace(k,str(symbols[k]))
81 break
82
83 input=pre+str(eval(mid))+post
84
85 m=exp.search(input)
86
87 return input
88
89 - def eval(self,input,vals):
90 """Gets a string, replaces all the strings between $$
91 with the evaluation of the expressions
92 @param input: the input string
93 @param vals: vector with the values or a dictionary
94 @returns: The string with the replaced expressions"""
95
96 return self.doCalcOnString("$"+input+"$",vals)
97