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('Email.py'):
lines.append(line)
text=''.join(lines)
print(field_pat.sub(replacement,text))
以上是一段可以把特定文件中的字符串格式化,我在Email.py中放的30+40=[30+40]没问题,能装换成30+40=70, 但是如果在Email.py里放这段代码[name='Bless']hello,[name],就会报错NameError: name 'name' is not defined,可是我已经在Email.py里声明了呀。。求助!这是python3,不知道是不是哪里写错了。。
已解决!!!