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

相关文章
相关标签/搜索