eval
evaluates expressions, not statements, so you need to pass it the print
function, not the print
statement. By default, print
is a statement in Python 2, and the print
statement doesn't exist in Python 3. However, the print
function is available in recent versions of Python 2 via a __future__
import. The print
function is actually defined in those versions of Python 2 but it's masked by the print
statement; the import makes the print
statement unavailable, thus exposing the print
function.
Demo, tested on Python 2.6.6:
from __future__ import print_function
eval("print('foobar')")
output
foobar
BTW, it's generally not a good idea to use eval
or exec
, unless you have no alternative. They are relatively slow, and have security risks if you pass them unsanitized strings to evaluate / execute. For details, please see Eval really is dangerous by SO veteran Ned Batchelder. To evaluate simple Python literals you can use ast.literal_eval
.