gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:11 24 4
gpt4 key购买 nike

我在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com