在Python中评估动态生成的语句 [英] Evaluating dynamically generated statements in Python
问题描述
我需要动态生成python代码并使用eval()函数执行它.
I need to dynamically generate python code and execute it with eval() function.
我想做的是生成一些导入"和分配值".我的意思是,我需要生成此字符串以对其进行评估eval(x)
.
What I would like to do is to generate some "imports" and "assign values". I mean, I need to generate this string to evaluate it eval(x)
.
x = """
import testContextSummary
import util.testGroupUtils
testDb = [testContextSummary.TestContextSummary,
testGroupUtils.testGroupUtils.TestGroupUtils]
""" # x is automatically generated
eval(x)
... use testDb ...
我尝试使用此代码,但是eval()返回无法识别import
的错误,因此我尝试了此代码.
I tried with this code, but eval() returns an error not recognizing import
, so I tried this code.
x = """
testContextSummary = __import__("testContextSummary")
testGroupUtils = __import__("util.testGroupUtils")
testDb = [testContextSummary.TestContextSummary,
testGroupUtils.testGroupUtils.TestGroupUtils]
""" # x is automatically generated
eval(x) # error
我再次遇到错误,不允许执行赋值语句.
I again got an error not allowing assignment statement.
有什么方法可以执行动态生成的python脚本,并使用评估结果?
Is there any way to execute dynamically generated python script, and use the result from the evalution?
推荐答案
您想要的是exec
而不是eval
.
>>> s = "x = 2"
>>> exec s
>>> x
2
当然,请不要在不受信任的字符串上使用exec
...
Of course, please don't use exec
on untrusted strings ...
这篇关于在Python中评估动态生成的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!