Python eval()函數

Python eval()

參數說明

The eval() takes three parameters:html

  • 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代碼執行,並返回執行結果。官方文檔是這樣說的:python

The expression argument is parsed and evaluated as a Python expressionexpress

例子

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未定義,因此報錯app

疑惑

這個東西存在的意義?在stackoverflow看到了一個例子:ui

>>> 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。this

注意

  • 既然能執行字符串,那os.system("rm -rf /")確定也能夠了;因此須要注意下
  • 另外兩個參數的用法可見參考2

參考

https://stackoverflow.com/questions/9383740/what-does-pythons-eval-dolua

http://www.javashuo.com/article/p-zhcuehdb-de.htmlcode

https://www.programiz.com/python-programming/methods/built-in/evalhtm

相關文章
相關標籤/搜索