标题似乎很愚蠢,但我不知道如何准确表达,对不起。
我有一个程序需要评估一些用户代码(通过 RestrictedPython 以确保安全),我想将一个函数放入 eval 的全局变量中,以便它可以在 eval 时向我打印一些调试信息,例如(简化):
class UserException(Exception):
pass
def err(msg):
# ? how to get the globals variable in eval ?
A = globals().get('A', 'A not found')
return UserException("%s and A's value is %r" % (msg, A))
g = {
'err': err,
'A': None,
'__builtins__': {},
}
print eval('A or err("A not true")', g)
这将给出结果:
A not true and A's value is 'A not found'
在这里使用 'globals()' insde 'err' 当然是错误的。但是我怎样才能在'err'中获得'g'中的值?