#templates.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)
现在编辑两个文件,通过调用这个脚本来处理:
cat > magnus.txt
[name = 'Magnus Lie Hetland' ]
[email = 'magnus@foo.bar' ]
[language = 'python' ]
cat > template.txt
[import time]
Dear [name]. I would like to learn how to program. I hear you use the [language] a lot.
Please help me to learn
Oscar
现在来调用: python templates.py magnus.txt template.txt
结果:
Dear Magnus Lie Hetland.
I would li to learn how to program. I hear you use the python a lot.
Please help me to learn
Oscar
templates.py脚本把template.txt中[]定义的变量替换成了magnus.txt中定义好的值