Python字符串格式化的问题

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,不知道是不是哪里写错了。。
已解决!!!

import fileinput, re

field_pat = re.compile(r'\[(.+?)\]')
scope = {}

def replacement(match):
code = match.group(1)
try:
return str(eval(code, scope))
except Exception as ex:
exec(code, scope)
return ''

lines = []
for line in fileinput.input('Email.py'):
lines.append(line)
print lines
text = ''.join(lines)
print(field_pat.sub(replacement, text))

eval(expression, global=None, local=None)
参数是字符串和可选的global和local。global应当为一个字典文件,local应为一个映射对象。
expression参数将被处理为一个python的表达式(严格来说,是一串条件语句),global和local参数将被用来当做全局和局部的命名空间。
exec(object[,global,[locals])
这个函数能够为python提供动态的代码执行功能。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-02-23
怎么解决的?
相似回答