3

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?

2 Answers 2

3

You want exec instead of eval.

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

prosseek: It's because exec() can handle multiple lines of Python, whereas eval() only evaluates a single expression. Be safe.
@martineau: I didn't see the original comment, but the same caveats with exec apply equally to eval and it has nothing to do with multiple lines of code ... (__import__('os').remove('important_file'))
0

This may also work:

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

1 Comment

While that might work in this particular case, things could get tricky if there were multiple names defined or there was more complicated logic in the dynamically generated code, like if/else constructs and/or function/class definitions, etc -- all of which exec() ought to be able to handle.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.