Python eval()
参数说明
The eval() takes three parameters:
- expression - this string as parsed and evaluated as a Python expression
- globals (optional) - a dictionary
- locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.
作用
将字符串参数当作Python代码执行,并返回执行结果。官方文档是这样说的:
The expression argument is parsed and evaluated as a Python expression
例子
In [1]: s = 'abc'
In [1]: s = 'abc'
In [2]: str(s)
Out[2]: 'abc'
In [7]: eval('x')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-e5b9369fbf53> in <module>()
----> 1 eval('x')
<string> in <module>()
NameError: name 'x' is not defined
In [8]: eval('s')
Out[8]: 'abc'
字符串 s 已经定义过,执行没问题;x未定义,所以报错
疑惑
这个东西存在的意义?在stackoverflow看到了一个例子:
>>> input('Enter a number: ')
Enter a number: 3
>>> '3'
>>> input('Enter a number: ')
Enter a number: 1+1
'1+1'
>>> eval(input('Enter a number: '))
Enter a number: 1+1
2
>>>
>>> eval(input('Enter a number: '))
Enter a number: 3.14
3.14
这样区别就很明显了吧,上面的接收到的是str,下面经过eval处理后,变成了float。
注意
- 既然能执行字符串,那os.system("rm -rf /")肯定也可以了;所以需要注意下
- 另外两个参数的用法可见参考2
参考
https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do
https://www.cnblogs.com/Xuuuuuu/p/10127029.html
https://www.programiz.com/python-programming/methods/built-in/eval