python - Eval 不适用于多行字符串

标签 python eval

我在使用 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 ,它区分(除其他外) file inputexpression 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 无法防范恶意用户,如果您使用它,它们可以而且接管网络进程。

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

关于python - Eval 不适用于多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30671563/

相关文章:

python - Python 中的 Windows 7 MARGINS 结构

python - 检查参数是按位置还是通过关键字传递的

javascript - 如何避免在此示例中使用 `eval()`?

javascript - 为什么 (0 || eval) 在 Opera 中不被视为间接?

c# - 在 C# 中实现 JS Eval

javascript - 获取 "window"对象进行评估,并列出所有变量? Javascript 评估内联 html

python - 使用 Hadoop Streaming 和 Python 在 Map Reduce 中进行叉积

python - 名称 'self' 未定义

python - 在 Python 中递归复制文件或目录

PHP 验证约束列表