博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python eval()函数的妙用和滥用
阅读量:4171 次
发布时间:2019-05-26

本文共 1376 字,大约阅读时间需要 4 分钟。

>>> help(eval)Help on built-in function eval in module __builtin__:eval(...)    eval(source[, globals[, locals]]) -> value    Evaluate the source in the context of globals and locals.    The source may be a string representing a Python expression    or a code object as returned by compile().    The globals must be a dictionary and locals can be any mapping,    defaulting to the current globals and locals.    If only globals is given, locals defaults to it.>>>

eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果:

>>> s='8*8'>>> eval(s)64>>> eval('2+5*4')22>>> x=1>>> y=4>>> eval('x+y')5>>> eval('98.9')98.9>>> eval('9.9\n')9.9>>> eval('9.9\n\t\r  \t\r\n')9.9
可以把list,tuple,dict和string相互转化:

>>> l = "[2,3,4,5]">>> ll=eval(l)>>> ll[2, 3, 4, 5]>>> type(ll)
>>> d="{'name':'python','age':20}">>> dd=eval(d)>>> type(dd)
>>> dd{'age': 20, 'name': 'python'}>>> t='(1,2,3)'>>> tt=eval(t)>>> type(tt)
>>> tt(1, 2, 3)>>>
eval()函数功能强大,但也很危险,若程序中有以下语句:

s=raw_input('please input:')print eval(s)
下面举几个被恶意用户使用的例子:

1》运行程序,如果用户恶意输入:

please input:__import__('os').system('dir')

则eval()之后,当前目录文件都会展现在用户前面。。。

2》运行程序,如果用户恶意输入:

please input:open('data.py').read()

如果,当前目录中恰好有一个文件,名为data.py,则恶意用户变读取到了文件中的内容。。。

3》运行程序,如果用户恶意输入:

please input:__import__('os').system('del delete.py /q')

如果,当前目录中恰好有一个文件,名为delete.py,则恶意用户删除了该文件。。。
/q :指定静音状态。不提示您确认删除。

类似文章,请参考:

转载地址:http://cnyai.baihongyu.com/

你可能感兴趣的文章
C++程序员技术需求规划(发展方向)
查看>>
A Game of Thrones(59)
查看>>
2018.3.19
查看>>
A Game of Thrones(97)
查看>>
A Game of Thrones(98)
查看>>
2018.3.20
查看>>
2018.3.21
查看>>
2018.3.22
查看>>
2018.3.23
查看>>
A Game of Thrones(102)
查看>>
2018.4.29
查看>>
2018.4.30
查看>>
2018.4.31
查看>>
2018.4.32
查看>>
2018.4.33
查看>>
《python基础教程》答案(第一章)
查看>>
2018.4.34
查看>>
2018.4.35
查看>>
2018.4.36
查看>>
我为什么要写博客
查看>>