(在将此类代码投入生产之前,请参阅末尾的默认安全警告!)
其他答案很好地解释了exec 和eval 之间的区别。
尽管如此,我发现自己想要像x=1; y=2; x+y 这样的输入而不是强迫人们写:
def f():
x = 1
y = 2
return x + y
对代码进行字符串操作来构建这种功能是一项冒险的事情。
我最终使用了以下方法:
def multiline_eval(expr, context):
"Evaluate several lines of input, returning the result of the last line"
tree = ast.parse(expr)
eval_expr = ast.Expression(tree.body[-1].value)
exec_expr = ast.Module(tree.body[:-1])
exec(compile(exec_expr, 'file', 'exec'), context)
return eval(compile(eval_expr, 'file', 'eval'), context)
这会解析python代码;使用 ast 库重建除最后一行之外的所有内容的 ast;最后一行,执行前者并评估后者。
安全警告
这是您必须附加到eval 的强制性安全警告。
由非特权用户提供的Eval'ing 和exec'ing 代码当然是不安全的。在这些情况下,您可能更喜欢使用另一种方法,或者考虑使用 ast.literal_eval。 eval 和 exec 往往不是好主意,除非你真的想为你的用户提供 python 的全部表达能力。