# 创建模板处理系统
(python_scripts) [root@mha-1 python_scripts]# cat template.py
import fileinput, re
# 与使用方括号扩起来的字段匹配
field_pat = re.compile(r'\[(.+?)\]')
# 让我们把变量收集到这里:
scope = {}
# 用于调用 re.sub
def replacement(match):
code = match.group(1)
try:
# 如果字段为表达式,就返回其结果
return str(eval(code, scope))
except SyntaxError:
# 否则在当前作用域内执行该赋值语句
exec(code, scope)
# 并返回一个空字符串
return ''
# 获取所有文本合并成一个字符串
lines = []
for line in fileinput.input():
lines.append(line)
text = ''.join(lines)
# 替换所有与字段模式匹配的内容:
print(field_pat.sub(replacement, text))
# 创建定义文件
(python_scripts) [root@mha-1 python_scripts]# cat magnus.txt [name = 'Magnus Lie Hetland']
[email = 'magnus@foo.bar']
[language = 'python']
# 创建模板文件
(python_scripts) [root@mha-1 python_scripts]# cat template.txt
[import time]
Dear [name],
I would like to learn how to program.I hear you
use the [language] language a log -- is it somethis I
should consider?
And, by the way,is [email] your correct email address?
Fooville,[time.asctime()]
Oscar Frozzbozz
# 使用定义文件和模板文件生成最终的想要的效果
(python_scripts) [root@mha-1 python_scripts]# python template.py magnus.txt template.txt
Dear Magnus Lie Hetland,
I would like to learn how to program.I hear you
use the python language a log -- is it somethis I
should consider?
And, by the way,is magnus@foo.bar your correct email address?
Fooville,Mon Jan 27 20:21:17 2020
Oscar Frozzbozz