将任何字符串作为python表达式求值:
eval()方法:
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
用法:
>>> eval("x*5",{}, {})
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
eval("x*5",{}, {})
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
>>> eval("x*5",{"x":x},{})
25
>>> import math
>>> eval("math.sqrt(x)",{"x":x},{})
Traceback (most recent call last):
File "<pyshell#123>", line 1, in <module>
eval("math.sqrt(x)",{"x":x},{})
File "<string>", line 1, in <module>
NameError: name 'math' is not defined