如何在Python中执行包含Python代码的字符串?


不要对可能来自程序外部的任何形式的数据使用eval(或exec)。这是一个严重的安全风险。您允许数据的作者在您的计算机上运行任意代码。如果你在这里是因为你想在你的Python程序中按照一个模式创建多个变量,你几乎肯定有一个XY问题。完全不要创建这些变量——相反,适当地使用列表或字典。


当前回答

其他回答

在本例中,使用exec函数将字符串作为代码执行。

import sys
import StringIO

# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()

code = """
def f(x):
    x = x + 1
    return x

print 'This is my output.'
"""

# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr

exec code

# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

print f(4)

s = codeErr.getvalue()

print "error:\n%s\n" % s

s = codeOut.getvalue()

print "output:\n%s" % s

codeOut.close()
codeErr.close()

Eval()只是用于表达式,而Eval ('x+1')可以工作,Eval ('x=1')则不能工作。在这种情况下,最好使用exec,甚至更好:尝试找到一个更好的解决方案:)

查看eval:

x = 1
print eval('x+1')
->2

你可以使用exec完成代码的执行,就像下面的IDLE会话一样:

>>> kw = {}
>>> exec( "ret = 4" ) in kw
>>> kw['ret']

4

我尝试了很多方法,但唯一有效的方法是:

temp_dict = {}
exec("temp_dict['val'] = 10") 
print(temp_dict['val'])

输出:

10