评估不适用于多行字符串 [英] Eval not working on multi-line string
问题描述
我在使用python eval函数执行多行字符串时遇到问题/
I am having issues with executing a multi-line string with the python eval function/
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 表达式 ,而不是语句。函数定义是语句,而不是表达式。
eval
can only evaluate Python expressions, not statements. A function definition is a statement, not an expression.
使用 exec
执行Python语句。
Use exec
to execute Python statements.
请参见 顶级组件文档,该文档与众不同(以及其他)之间 文件输入 和 表达式输入 :
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:
[...]
- 在解析传递给
exec
语句的字符串时;
- when parsing a string passed to the
exec
statement;
和
[...]
eval()
的字符串参数必须具有以下格式:
[...] The string argument to
eval()
must have the following form:
eval_input ::= expression_list NEWLINE*
不要不要使用它来执行不受信任的用户提供的文本。 eval()
和 exec
不能防范恶意用户,他们可以并且将
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.
实际上,除了以一次性方式运行代码外,没有安全的方法可以执行此操作虚拟机,所有服务均已牢固关闭。运行新的虚拟机以获取新代码,完成后或超时后丢弃整个VM。
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.
这篇关于评估不适用于多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!