简体   繁体   English

评估不适用于多行字符串

[英]Eval not working on multi-line string

I am having issues with executing a multi-line string with the python eval function/我在使用 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 can only evaluate Python expressions , not statements. eval只能评估Python表达式,而不是语句。 A function definition is a statement, not an expression.函数定义是语句,而不是表达式。

Use exec to execute Python statements.使用exec执行 Python 语句。

See the 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;解析传递给exec语句的字符串时;

and

[...] The string argument to eval() must have the following form: [...] eval()的字符串参数必须具有以下形式:

 eval_input ::= expression_list NEWLINE*

Do NOT use this to execute untrusted user-supplied text.不要使用此执行不可信的用户提供的文本。 eval() and exec are not guarded against malicious users, and they can and will take over the web process if you use this. eval()exec没有防范恶意用户,如果您使用它,它们可以并且接管 Web 进程。

In fact, there is no 'safe' way to ever do this, other than running the code in a throw-away virtual machine with all services firmly bolted shut.事实上,没有“安全”的方法可以做到这一点,除了在所有服务都牢牢关闭的一次性虚拟机中运行代码。 Run a new virtual machine for new code, throw away the whole VM when done or after a timeout.为新代码运行一个新的虚拟机,完成或超时后丢弃整个虚拟机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM