[英]Python Eval executing environment
I do not understand what environment a eval or exec statement executes in. You can pass both global and local scopes to them but I don't quite understand what this means. 我不了解eval或exec语句在什么环境中执行。您可以将全局范围和局部范围传递给它们,但我不太理解这意味着什么。 Does python create an anonymous module for them, and if that is the case how do the global and local scope differ? python是否会为它们创建一个匿名模块,如果是这种情况,则全局范围和局部范围有何不同?
Does it run it like it was an anonymous function? 它像一个匿名函数一样运行吗? If that was the case the global and local scopes would make more sense to me, although would you still need to call global var
to prevent python from making a local variable on assignment? 如果是这样的话,尽管我仍然需要调用global var
来防止python在赋值时创建局部变量,但全局和局部作用域对我来说更有意义。
And here is some code to show what I am actually trying to do. 这是一些代码来显示我实际上正在尝试执行的操作。
# module level vars
result = ''
allowed_builtins = {"__builtins__":{'int':int, 'str':str, 'range':range, 'dir':dir,
'zip':zip
},
"result":result}
In class 在班上
def _exec(self, answer, function_name, input):
global result
exec_string = answer + '\n'
exec_string += 'global result; result = %s(%s)' % (function_name, input)
exec exec_string in allowed_builtins, {}
return result
I would like the var result in my scope to be able to be set from within the eval/exec's scope. 我希望可以在eval / exec的范围内设置我范围内的var结果。
The "local" dictionary is where all names are being set during an exec
or eval
; “本地”字典是在exec
或eval
期间设置所有名称的地方; the "global" one is used for lookup of names not found in the "local" one, but names aren't set there unless you're exec
ing code that includes a global
statement. “全局”名称用于查找在“本地”名称中找不到的名称,但是除非您正在exec
包含global
语句的代码,否则不会在其中设置名称。
No module object is created intrinsically by either eval
or exec
, nor is any function object, anonymous or otherwise (again, of course: unless you exec
statements such as def
, etc). eval
或exec
不会本质上创建模块对象,匿名或其他方式也不会创建任何函数对象(当然,当然:除非您exec
def
等exec
语句)。
Edit : for example, given the OP's code, and assuming _exec
is a free-standing function since the OP's giving no class
where it could live, add at the end: 编辑 :例如,给定OP的代码,并假定_exec
是一个独立的函数,因为OP没有给出可能存在的class
,请在末尾添加:
print 'one: %r' % _exec(None, '"foo"', 'range', 7)
print 'two: %r' % allowed_builtins['result']
and you'll see this output: 您将看到以下输出:
one: ''
two: [0, 1, 2, 3, 4, 5, 6]
the result
in the __dict__
of the current module is of course not affected (how could it conceivably be , since that dict is never passed to the exec
in question?!) -- the allowed_builtins
dictionary is of course the one affected, since it's the dict passed as the "global dictionary" and there is a global
statement in the string being exec
uted! 当前模块的__dict__
的result
当然不会受到影响(可以想象是怎么回事,因为该dict永远不会传递给有问题的exec
?!)- allowed_builtins
字典当然是受影响的那allowed_builtins
,因为它是字典的“全球词典”过去, 有一个global
的字符串中的语句是exec
贡献!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.