为什么我不能直接使用eval(entire_string),为什么我需要使用parser.expr(entire_string).compile()?
Why I cannot use eval(entire_string) straightaway, why do I need to use parser.expr(entire_string).compile()?
Source code for building a calculator using Tkinter
parser.expr(entire_string).compile()
VS eval(entire_string)
版本 1:
import parser
entire_string = '1+2'
a = parser.expr(entire_string).compile()
result = eval(a)
版本 2:
entire_string = '1+2'
result = eval(entire_string)
使用 parser.expr(entire_string).compile()
有什么意义,为什么不直接使用 eval(entire_string)
?
这是因为 python 中的 eval 很危险。如果字符串是由用户输入的,那么他们就可以在你的机器上执行任意代码。如果它在远程服务器上 运行ning,这尤其危险。
解析器将只解析一个表达式和 return 一个值,不允许将任意 python 代码解析为 运行。
Source code for building a calculator using Tkinter
parser.expr(entire_string).compile()
VS eval(entire_string)
版本 1:
import parser
entire_string = '1+2'
a = parser.expr(entire_string).compile()
result = eval(a)
版本 2:
entire_string = '1+2'
result = eval(entire_string)
使用 parser.expr(entire_string).compile()
有什么意义,为什么不直接使用 eval(entire_string)
?
这是因为 python 中的 eval 很危险。如果字符串是由用户输入的,那么他们就可以在你的机器上执行任意代码。如果它在远程服务器上 运行ning,这尤其危险。
解析器将只解析一个表达式和 return 一个值,不允许将任意 python 代码解析为 运行。