#template.py
import fileinput, re
field_pat = re.compile(r'\[(.+?)\]')
scope = {}
def replacement(match):
code = match.group(1)
try:
return str(eval(code, scope))
except SyntaxError:
exec code in scope
return
lines = []
for line in fileinput.input():
lines.append(line)
text = ''.join(lines)
print field_pat.sub(replacement, text)
#text.py
[x = 1]
[y = 2]
The sum of [x] and [y] is [x + y]
If I execute "python template.py text.py" in command line, if will print 'The sum of 1 and 2 is 3'. In the file template.py, replacement() is a function, why it is an argument of sub() function and it does not have argument?(it's supposed to take an match object as argument) And also, what is the scope dictionary for if it is empty?? Many thanks!!!