Evaluating dynamically generated statements in Python

吃可爱长大的小学妹 提交于 2019-12-11 02:57:09

问题


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)


来源:https://stackoverflow.com/questions/16951937/evaluating-dynamically-generated-statements-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!