评估方法在Python?
Pythoneval()方法用于将表达式字符串解析为python表达式,然后在程序中运行python表达式。
语法
通用的pythoneval()方法语法为:
eval(expression, globals=None, locals=None)
哪里:
expression:必需的字符串参数,这是正被解析并作为python表达式执行的表达式字符串。
globals:可选参数是一个字典,用于指定可用于执行的表达式。如果未明确提及,则可以使用标准的内置方法,例如'__builtins__':None元素。
locals:可选参数,用于指定eval()函数可用的局部变量和方法。
现在,为了更好地了解eval()方法,让我们通过不同的示例来了解它。
简单的eval()方法
str1 = 'Hello' print(eval('str1 =="Hello"')) print(eval('str1 + ", Python"'))
输出结果
True Hello, Python
具有用户输入的Pythoneval()方法
from math import * for l in range(1,3): func = input("Enter Math Function to Evaluate:\n") try: print(eval(func)) except Exception as ex: print(ex) break print('Done')
输出结果
Enter Math Function to Evaluate: abs(-42) 42 Enter Math Function to Evaluate: max(12, 3, 4 , 2, 17) 17 Done
Pythoneval()全局变量和局部变量
在了解需要传递给eval()方法的函数之前,让我们获取全局和局部作用域中存在的所有函数和变量的列表。
from math import * def square_root(n): return sqrt(n) # Print current global symbol table as a dictionary print('List of Global symbols:\n',globals()) #Print current local symbol table as a dictionary print('\nList of Local symbols:\n',locals()) #print list of names in the current local scope print('\nList of names in current local scope:\n',dir())
输出结果
List of Global symbols: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Python/Python361/eval_example1.py', 'acos': <built-in function acos>, 'acosh': <built-in function acosh>, 'asin': <built-in function asin>, 'asinh': <built-in function asinh>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'atanh': <built-in function atanh>, 'ceil': <built-in function ceil>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'cosh': <built-in function cosh>, 'degrees': <built-in function degrees>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'exp': <built-in function exp>, 'expm1': <built-in function expm1>, 'fabs': <built-in function fabs>, 'factorial': <built-in function factorial>, 'floor': <built-in function floor>, 'fmod': <built-in function fmod>, 'frexp': <built-in function frexp>, 'fsum': <built-in function fsum>, 'gamma': <built-in function gamma>, 'gcd': <built-in function gcd>, 'hypot': <built-in function hypot>, 'isclose': <built-in function isclose>, 'isfinite': <built-in function isfinite>, 'isinf': <built-in function isinf>, 'isnan': <built-in function isnan>, 'ldexp': <built-in function ldexp>, 'lgamma': <built-in function lgamma>, 'log': <built-in function log>, 'log1p': <built-in function log1p>, 'log10': <built-in function log10>, 'log2': <built-in function log2>, 'modf': <built-in function modf>, 'pow': <built-in function pow>, 'radians': <built-in function radians>, 'sin': <built-in function sin>, 'sinh': <built-in function sinh>, 'sqrt': <built-in function sqrt>, 'tan': <built-in function tan>, 'tanh': <built-in function tanh>, 'trunc': <built-in function trunc>, 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': <function square_root at 0x055246F0> } List of Local symbols: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Python/Python361/eval_example1.py', 'acos': <built-in function acos>, 'acosh': <built-in function acosh>, 'asin': <built-in function asin>, 'asinh': <built-in function asinh>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'atanh': <built-in function atanh>, 'ceil': <built-in function ceil>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'cosh': <built-in function cosh>, 'degrees': <built-in function degrees>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'exp': <built-in function exp>, 'expm1': <built-in function expm1>, 'fabs': <built-in function fabs>, 'factorial': <built-in function factorial>, 'floor': <built-in function floor>, 'fmod': <built-in function fmod>, 'frexp': <built-in function frexp>, 'fsum': <built-in function fsum>, 'gamma': <built-in function gamma>, 'gcd': <built-in function gcd>, 'hypot': <built-in function hypot>, 'isclose': <built-in function isclose>, 'isfinite': <built-in function isfinite>, 'isinf': <built-in function isinf>, 'isnan': <built-in function isnan>, 'ldexp': <built-in function ldexp>, 'lgamma': <built-in function lgamma>, 'log': <built-in function log>, 'log1p': <built-in function log1p>, 'log10': <built-in function log10>, 'log2': <built-in function log2>, 'modf': <built-in function modf>, 'pow': <built-in function pow>, 'radians': <built-in function radians>, 'sin': <built-in function sin>, 'sinh': <built-in function sinh>, 'sqrt': <built-in function sqrt>, 'tan': <built-in function tan>, 'tanh': <built-in function tanh>, 'trunc': <built-in function trunc>, 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': <function square_root at 0x055246F0> } List of names in current local scope: ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'square_root', 'tan', 'tanh', 'tau', 'trunc' ]
在下面我们可以看到,我们可以在eval函数中将globals值指定为空字典:
>>> print(eval('dir()', {})) ['__builtins__']
让我们看另一个示例,在该示例中,我们仅允许访问math模块中的一些方法。
from math import * for l in range(1, 4): func = input("Enter Math Function to Evaluate.\nAllowed Functions are: abs(x) and pow(x,y):\n") try: print(eval(func, {'absolute': abs, 'pow': pow})) except Exception as ex: print(ex) break print('Done')
输出结果
Enter Math Function to Evaluate. Allowed Functions are: abs(x) and pow(x,y): abs(-74) 74 Enter Math Function to Evaluate. Allowed Functions are: abs(x) and pow(x,y): pow(2,7) 128.0 Enter Math Function to Evaluate. Allowed Functions are: abs(x) and pow(x,y): sqrt(47) name 'sqrt' is not defined Done