一个强大的python模版脚本

释放双眼,带上耳机,听听看~!

#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中定义好的值

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++迭代器

2022-1-11 12:36:11

安全经验

Http与RPC通信协议的比较

2021-11-28 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索