> 文档中心 > Python eval()函数看这里就够了

Python eval()函数看这里就够了


eval函数在Python中具有非常重要的地位,熟练的使用eval函数能够为我们的Python编程提供很多的便利之处。在本文中我将详细记录eval函数在Python中的使用方法及它带来便利时带来的一些其他危害,希望您阅读完本文后能够有所收获。欢迎在文章下方留言共同交流学习。

Python eval()函数

目录

一、语法和参数

 二、expression参数示例

三、globals参数示例

四、locals参数示例 

五、eval函数的危险之处

六、eval函数官方文档 


       eval是Python的一个内置函数,功能十分强大,这个函数的作用是,返回传入字符串的表达式的结果。就是说:将字符串当成有效的表达式 来求值 并 返回计算结果。

eval函数就是实现list、dict、tuple与str之间的转化,同样str函数把list,dict,tuple转为为字符串 

eval(expression[, globals[, locals]])expression : 表达式。globals : (可选参数)变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。locals : (可选参数)变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

 

一、语法和参数

      在Python中evel()函数的语法格式为eval(expression, globals=None, locals=None),注意后面还有globals参数和locals参数。eval()函数用于执行一个字符串表达式,并且返回该表达式的值。与eval相近的有exec函数,该函数将会在另一篇文章详细讲解。

  • expression:表达式,上面提到evel函数用于执行一个字符串表达式,表达式的内容就放在此处。当表达式涉及到
  • globals该部分必须是字典!否则程序会出错。当定义了globals 参数之后eval函数的作用域会被限定在globals中。
  • locals:该参数掌控局部的命名空间,功能和globals类型,不过当参数冲突时,会执行locals处的参数。

 二、expression参数示例

a = 10print(eval("a+1")) #11

【解析】:因为此处没有指定globals和locals,所以直接执行expression部分的内容。该程序的效果等价于a=10 print(a+1)

三、globals参数示例

a = 10g = {'a': 10}print(eval('a+1', g)) #5

【解析】:因为现在指定了globals,所以在expression部分的作用域就是globals指定的字典范围内。所以此时外面的a=10被屏蔽,取用字典中的值。

四、locals参数示例 

a = 10b = 20c = 30g = {'a': 6, 'b': 8}t = {'b': 100, 'c': 10}print(eval('a+b+c', g, t))

 运行结果为116
【解析】:根据上面题目的练习我们知道了当有globals和locals时作用的范围域是在globals和locals中,所以a=10,b=20,c=30不会被应用。a和c的值分别去字典g和字典t中的值,当globals和locals中都有参数b时取locals中的值。所以a=6,b=100,c=10

五、eval函数的危险之处

       eval函数非常的方便,我们可以使用一行代码就实现计算器的功能print(eval(input('请输入')))。但是因为它具有可以将字符串转成表达式执行的特性,所以它也就可以去执行系统命令。这样很容易被别有用心的人用来执行系统命令,删除关键文件系统,比如用户恶意输入就会获得当前目录文件。 

 在cmd中执行eval("__import__('os').system('dir')")

C:\Users\华为>pythonPython 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> eval("__import__('os').system('dir')") 驱动器 C 中的卷是 Windows 卷的序列号是 8C97-DCB3 C:\Users\华为 的目录2022/01/01  21:57       .2022/01/01  21:57       ..2021/01/26  21:56       .android2021/04/16  11:24       .cache2021/08/21  15:49       .config2021/10/11  11:15       .dotnet2021/04/16  11:24       .eclipse2021/07/17  17:31       .idlerc2021/12/18  16:05 675 .labelImgSettings.pkl2021/08/18  23:06      1,435 .labelmerc2022/01/15  17:05       .p22021/10/16  23:57       .wxcloudbase2021/07/14  23:05       3D Objects2020/12/26  11:50       ansel2021/12/13  09:16       ch102021/12/13  09:16       ch112021/12/13  09:16       ch122021/12/13  09:16       ch132021/12/13  09:16       ch_72021/12/13  09:16       ch_82021/12/13  09:16       ch_92021/07/14  23:05       Contacts2022/01/15  17:02       Desktop2021/12/13  09:16       dierzhouzuoye2021/12/13  09:16       Diliuzhouzuoye2021/12/13  09:16       Diyicizuoye2021/12/03  21:09       Documents2022/01/17  10:22       Downloads2021/07/14  23:05       Favorites2021/10/11  10:24       Links2021/07/14  23:05       Music2021/12/04  22:01       OneDrive2021/04/16  10:27       PCManger2021/10/17  09:04       Pictures2020/02/07  10:52       Roaming2021/07/14  23:05       Saved Games2021/07/14  23:05       Searches2021/10/11  11:46       source2021/10/17  09:04       TEMP2021/12/13  09:16       TTTTest2021/07/14  23:05       Videos2021/12/13  09:16       Xiti3 2 个文件   2,110 字节40 个目录 12,118,945,792 可用字节0>>>

六、eval函数官方文档 

   The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.   The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If theglobals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:>>> x = 1>>> eval('x+1')2   This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has beencompiled with 'exec' as the mode argument, eval()‘s return value will be None.   Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().   See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

 统一声明:关于原创博客内容,可能会有部分内容参考自互联网,如有原创链接会声明引用;如找不到原创链接,在此声明如有侵权请联系删除。关于转载博客,如有原创链接会声明;如找不到原创链接,在此声明如有侵权请联系删除。