您不能在lambda
正文中使用语句,这就是您收到该错误的原因,lambda
只需要表达式。
但是在 Python 3exec
中是一个函数,并且在那里可以正常工作:
>>> t = lambda x: exec(x)
>>> t("print('hello')")
hello
在 Python 2 中,您可以使用compile()
with eval()
:
>>> t = lambda x: eval(compile(x, 'None','single'))
>>> strs = "print 'hello'"
>>> t(strs)
hello
帮助compile()
:
compile(...)
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
Compile the source string (a Python module, statement or expression)
into a code object that can be executed by the exec statement or eval().
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if non-zero, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or zero these statements do influence the compilation,
in addition to any features explicitly specified.