Eval 不适用于多行字符串

Eval not working on multi-line string

我在使用 python eval 函数/

执行多行字符串时遇到问题
code = ''' 

def main():
  print "this is a test"

main()

'''

eval(code)

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    eval(code)
  File "<string>", line 3
    def main():
      ^
SyntaxError: invalid syntax

eval 只能计算 Python expressions,不能计算语句。函数定义是语句,而不是表达式。

使用exec执行Python条语句。

参见 Top-level components document, which differentiates (among others) between file input and expression input:

file_input ::=  (NEWLINE | statement)*

This syntax is used in the following situations:

[...]

  • when parsing a string passed to the exec statement;

[...] The string argument to eval() must have the following form:

eval_input ::=  expression_list NEWLINE*

不要不要使用它来执行不受信任的用户提供的文本。 eval()exec 没有防范恶意用户,如果您使用它,他们可以并且 接管网络进程。

事实上,没有 'safe' 方法可以做到这一点,除了 运行 所有服务都牢牢关闭的一次性虚拟机中的代码。 运行 新代码的新虚拟机,完成后或超时后丢弃整个 VM。