当前位置: 移动技术网 > IT编程>脚本编程>Python > Python eval()函数

Python eval()函数

2020年01月16日  | 移动技术网IT编程  | 我要评论

如何制作幻灯片模板,清心游,龙田腾子

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://www.cnblogs.com/xuuuuuu/p/10127029.html

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网