我一直在寻找的Python代码动态评估,并遇到了eval()和compile()功能,以及exec声明.
有人可以解释之间的区别eval和exec怎样的不同模式,compile()适应吗?
我exec在一些Python 2代码中使用该语句,并且我试图使该代码与Python 2和Python 3兼容,但是在Python 3中,exec已经从语句变为函数.是否可以编写与Python 2和3兼容的代码?我已经阅读了Python 2和Python 3双重开发,但我对exec语句/函数更改的特定解决方案感兴趣.
我意识到这exec通常是气馁的,但我正在构建一个Eclipse插件,它在PyDev之上实现了实时编码.有关详细信息,请参阅项目页面.
寻找有关此代码引发的原因的详细解释SyntaxError.
def echo(x):
return x
def foo(s):
d = {}
exec(s, {}, d)
return dict((x,y) for x,y in d.items())
def bar(s):
d = {}
exec(s, {}, d)
return dict((x, echo(y)) for x,y in d.items()) # comment this to compile
s = 'a=1'
foo(s)
Run Code Online (Sandbox Code Playgroud)
File "test.py", line 11
exec(s, {}, d)
SyntaxError: unqualified exec is not allowed in function 'bar' it contains a
nested function with free variables
Run Code Online (Sandbox Code Playgroud)