如何通过另一个文件中另一个文件定义的变量来使用该文件中包含eval的函数? [英] How to use a function containing eval in a file by variable defined at another file from that another file?
问题描述
假设,我创建了一个python文件(FirstFile.py)名称,其中包含许多功能和其他内容.功能之一就是这个(当然,它是简化的):
Assume, I have created an python file (FirstFile.py) name which contains many functions and other things. One of the function is this (of course, it is simplified):
def func(string):
assert eval(string)
此外,我还创建了一个python文件,该文件从上述文件中导入func().然后,第二个python文件尝试执行以下过程:
Besides, I have created an python file which imports func() from the file mentioned above. Then this second python file try to execute following process:
from FirstFile import func
amk = 1
func("amk == 1")
当变量"amk"在第一个文件中时,没有任何问题.但是,当变量"amk"在第二个文件中时(如此处所示),将显示错误:
When variable "amk" is in the first file, no problem reveals. However, when variable "amk" is in the second file, which is illustrated here, an error reveals:
NameError: name 'amk' is not defined
您想请帮我解决这个问题吗?
Would you like to please help me solve this problem?
推荐答案
默认情况下,eval
在当前的本地/全局范围内执行,如果要指定其他环境,则可以执行以下操作:
by default eval
executes in the current local/global scope, if you want to specify a different environment you can do something like:
eval("x == 1", {"x":1})
因此您的函数可以使用可选的environ
参数:
so your function could take an optional environ
argument:
def func(string, environ=None):
assert eval(string, environ)
然后您可以从另一个以locals()
为环境的模块中调用该函数:
then you can call the function from the other module passing locals()
as the environment:
from FirstFile import func
amk = 1
func("amk == 1", locals())
作为旁注,我建议不要评估任意代码,尤其是当它来自另一个源/模块时,因为它可能偶然包含有害代码.
As a side note I'd recommend against evaluating arbitrary code especially if it is coming from another source / module as it could accidentally contain harmful code.
这篇关于如何通过另一个文件中另一个文件定义的变量来使用该文件中包含eval的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!