Python eval() 函数详解:语法、参数与安全风险

温以宁
温以宁
发布时间:2026-10-15 | 4人浏览过
原创

本文深入解析Python中eval()函数的语法结构,详细讲解expression、globals及locals三个参数的作用机制与优先级。通过具体代码示例展示变量作用域的覆盖规则,并重点强调eval执行任意字符串带来的系统命令执行风险,建议开发者谨慎使用或采用ast.literal_eval等安全替代方案。

一、语法和参数

在Python中,eval()函数的标准语法格式为eval(expression, globals=None, locals=None),其中除了核心表达式外,还包含可选的globals和locals参数。该函数的主要功能是执行一个字符串形式的Python表达式,并返回该表达式的计算结果。需要注意的是,与eval功能相似但用途不同的exec函数,将在后续独立文章中详细展开讨论。

  • expression参数用于指定需要执行的字符串表达式内容。这是eval()函数的核心输入,决定了最终计算或操作的对象。当表达式涉及变量引用时,变量的查找范围将受到后续参数配置的影响。
  • globals参数用于提供全局命名空间,其类型必须严格为字典(dict)。如果传入非字典类型,程序将抛出异常。一旦指定了globals参数,eval()函数的执行作用域将被限制在该字典所定义的范围内,外部全局变量将不再直接可见。
  • locals参数用于控制局部命名空间,其作用机制与globals类似,同样接受映射对象(如字典)。当globals和locals同时存在且包含相同的键名时,locals中的值具有更高优先级,eval()会优先从locals中获取变量值。

二、expression参数示例

a=10;
print(eval("a+1"))

运行结果为11

【解析】:由于示例中未指定globals和locals参数,eval()直接在全局作用域内执行expression部分的内容。该代码逻辑等价于先定义a=10,然后打印a+1的结果。

三、globals参数示例

a=10;
g={'a':4}
print(eval("a+1",g))

运行结果为5

【解析】:当指定了globals参数后,expression部分的作用域被限制在globals指定的字典范围内。此时,外部全局变量a=10被屏蔽,eval()从字典中查找变量a的值(即4),因此计算结果为4+1=5。

四、locals参数示例

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

运行结果为116

【解析】:通过前述示例可知,当同时提供globals和locals时,变量查找范围限定在这两个字典中,外部全局变量a=10、b=20、c=30均不可见。变量a和c的值分别从字典g和t中获取,分别为6和10。对于变量b,由于在globals和locals中均存在,根据优先级规则,取locals(即字典t)中的值100。最终计算为6+100+10=116。

五、eval函数的危险之处

eval函数虽然便捷,允许通过一行代码实现简易计算器功能(如print(eval(input('请输入')))),但其将字符串直接转为表达式执行的特性也带来了严重的安全隐患。恶意用户可利用此特性构造包含系统命令的字符串,从而执行删除关键系统文件等危险操作。因此,在处理不可信输入时,应极度谨慎使用eval()。

六、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 the
globals 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 been
compiled 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.

附eval()函数常见作用有

1、计算字符串中有效的表达式,并返回结果

>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> eval("n + 4")
85

2、将字符串转成相应的对象(如list、tuple、dict和string之间的转换)

>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval(a)
>>> b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> a = "{1:'xx',2:'yy'}"
>>> c = eval(a)
>>> c
{1: 'xx', 2: 'yy'}
>>> a = "(1,2,3,4)"
>>> d = eval(a)
>>> d
(1, 2, 3, 4)

3、将利用反引号转换的字符串再反转回对象

>>> list1 = [1,2,3,4,5]
>>> `list1`
'[1, 2, 3, 4, 5]'
>>> type(`list1`)
<type 'str'>
>>> type(eval(`list1`))
<type 'list'>
>>> a = eval(`list1`)
>>> a
[1, 2, 3, 4, 5]

总结

到此这篇关于Python eval() 函数的文章就介绍到这了,更多相关Python eval() 函数内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表