1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import re
from string import Template
g__TMPLVars = {'Dest_Name':'Mr.Toto', 'Aff_Date':'16 Mai 2010', 'Param':'OKeeeeeee'}
PATTERN = '(.*)<<<\%\%(.+)\%\%>>>(.*)'
def foo2(matchobj):
global g__TMPLVars
token = matchobj.group(2)
template = Template(token)
buffer = template.substitute(**g__TMPLVars)
try:
buffer = eval(buffer, locals(), globals())
except:
# string contains text => no evaluation
pass
return matchobj.group(1) + buffer + matchobj.group(3)
def foo3(param):
row = param+'\n'
return row*3
test_string = """
blah bla <<<%% ${Dest_Name}, Paris le ${Aff_Date} %%>>>
<<<%%foo3("${Param}")%%>>>
"""
template = re.sub(PATTERN, foo2, test_string)
print(template) |