开发者

How to evaluate arbitrary code in Python?

I'd like to be able to evaluate arbitrary code from a string in Python, including code composed of multiple statements, and statements that span multiple lines. The approaches I've tried so far have been to use exec and eval, but these seem to only be able to evaluate ex开发者_C百科pressions. I have also tried the code.InteractiveInterpreter class, but this also only seems to allow evaluation using eval, exec, or single-statement modes. I've tried splitting the code by line, but this fails to handle statements that span multiple lines. Is there a way to accomplish this?


exec seems to be what you are looking for:

s = """
for i in range(5):
    print(i)
"""
exec s

prints

0
1
2
3
4

eval() only handles expressions, but exec handles arbitrary code.


Can you tell me the issue you're facing with exec? This seems to work for me.

>>> foo = """
... def baz():
...   print "Hello"
... """
>>> 
>>> exec foo
>>> baz()
Hello
>>> 

exec also has an in form where you can insert the result of the evaluation into a namespace which is better than polluting the current one.


Just to build on what sven is saying there is a conditional part to using exec which allows the specification of a namespace to execute inside for example when exec code in the global namespace you can do

exec "code" in globals()

or if you want to specify your own namespace hand it a dict

di = {}
exec "code" in di


Update for Python 3: Just as with print, exec now has to be used with parenthesis:

exec("print(1)")

Some things have changed in the behavior, see this thread

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜