Python eval() 參數說明 The eval() takes three parameters: expression this string as parsed and evaluated as a Python expression globals (optional) a dicti ...
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