Evaluating dynamically generated statements in Pyt

2019-07-12 09:43发布

问题:

I need to dynamically generate python code and execute it with eval() function.

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 ...

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.

Is there any way to execute dynamically generated python script, and use the result from the evalution?

回答1:

You want exec instead of eval.

>>> s = "x = 2"
>>> exec s
>>> x
2

Of course, please don't use exec on untrusted strings ...



回答2:

This may also work:

x = """[
        __import__("testContextSummary").TestContextSummary, 
        __import__("util.testGroupUtils").testGroupUtils.TestGroupUtils]
"""
testDB=eval(x)


标签: python eval