这个标题看起来很愚蠢,但我不知道如何准确地表达它,对不起。
我有一个程序,需要评估一些用户代码(通过RestrictedPython的安全性),我想把一个函数放在评估的全局变量中,这样当评估时,它可以打印出一些调试信息给我,例如(简化):
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()‘加上'err’当然是错误的。但是我怎样才能在'err‘里面得到'g’的值呢?
发布于 2012-09-21 17:18:16
您可以将其作为默认参数传递给g:
def err(msg, g=g):
A = g['A']
return UserException("%s and A's value is %r" % (msg, A))将给出结果:A not true and A's value is None。
https://stackoverflow.com/questions/12527525
复制相似问题