Reputation: 190679
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?
Upvotes: 3
Views: 2311
Reputation: 97918
This may also work:
x = """[
__import__("testContextSummary").TestContextSummary,
__import__("util.testGroupUtils").testGroupUtils.TestGroupUtils]
"""
testDB=eval(x)
Upvotes: 0
Reputation: 309831
You want exec
instead of eval
.
>>> s = "x = 2"
>>> exec s
>>> x
2
Of course, please don't use exec
on untrusted strings ...
Upvotes: 3