eval函数python

Python eval() function is used to parse an expression string as python expression and then execute it.

Python eval()函数用于将表达式字符串解析为python表达式,然后执行它。

Python eval()函数 (Python eval() function)

Python eval() function signature is:

Python eval()函数签名为:

eval(expression, globals=None, locals=None)

expression – mandatory string parameter, this is being parsed and executed as python expression.

expression –必需的字符串参数,正在作为python表达式进行解析和执行。

globals – dictionary used to specify the expressions available to execute. Standard built-in methods are available if not explicitly restricted using '__builtins__': None element.

globals –字典,用于指定可用于执行的表达式。 如果未使用'__builtins__': None明确限制,则可以使用标准的内置方法'__builtins__': None元素。

locals – used to specify the local variables and methods available to eval() function.

locals –用于指定eval()函数可用的局部变量和方法。

Python eval()示例 (Python eval() example)

Let’s first look at a simple example of python eval() function.

我们首先来看一个简单的python eval()函数示例。

x = 1print(eval('x==1'))print(eval('x+2'))

Output:

输出:

True
3

带有用户输入的Python eval() (Python eval() with user input)

Above example of eval() function is very limited and doesn’t justify its power. The power of eval() function lies in dynamic execution of statements. We can execute arbitrary code objects using eval() function.

上面的eval()函数示例非常有限,不能证明其功能合理。 eval()函数的功能在于语句的动态执行。 我们可以使用eval()函数执行任意代码对象。

Let’s look at a more complex example where we will ask the user to enter functions to execute.

让我们看一个更复杂的示例,在该示例中,我们将要求用户输入要执行的功能。

# eval() with user input
from math import *for l in range(1, 3):func = input("Enter Math Function to Evaluate:\n")try:print(eval(func))except Exception as ex:print(ex)break
print('Done')

Below image shows a sample execution of the above python script.

下图显示了上述python脚本的示例执行。

Without eval function, we can’t execute the user entered commands. This is the power of eval() function.

没有eval函数,我们将无法执行用户输入的命令。 这是eval()函数的功能。

使用eval()函数的安全风险 (Security Risks with eval() function)

With Great Power Comes Great Responsibility is very true if you are allowing user input to be executed as a command.

强大的力量伴随而来如果您允许用户输入作为命令来执行,那么伟大的责任就非常重要。

What if we have os module imported and user enters os.system('rm -rf /') command to be executed. This will start deleting system files and corrupt our environment.

如果导入了os模块并且用户输入os.system('rm -rf /')命令执行该os.system('rm -rf /') ? 这将开始删除系统文件并破坏我们的环境。

That’s why when you are using eval() function to execute user input code, you need to make sure that user entered data is checked first and if they are fine then only its executed. This is when globals and locals parameters come in handy.

这就是为什么在使用eval()函数执行用户输入代码时,需要确保首先检查用户输入的数据,如果它们很好,则仅对其执行。 这是全局和局部参数派上用场的时候。

Python eval()全局变量和局部变量 (Python eval() globals and locals)

Before we decide what functions we should make available to eval(), we need to find out what all functions and variables are present in the global and local scope. We can find this information using globals(), locals(), and dir() builtin functions.

在决定应将哪些函数提供给eval()之前,我们需要找出全局和局部范围内存在的所有函数和变量。 我们可以使用内置函数globals()locals()dir()找到此信息。

Let’s look at an example where we will find out the functions and variables available in global and local scope.

让我们看一个例子,我们将找出全局和局部范围内可用的函数和变量。

from math import *def square_root(n):return sqrt(n)print(globals()) # dictionary representing the current global symbol table.
print(locals()) # dictionary representing the current local symbol table.
print(dir()) # list of names in the current local scope

Output:

输出:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x105b11400>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/eval_example.py', '__cached__': None, 'acos': <built-in function acos>, 'acosh': <built-in function acosh>, 'asin': <built-in function asin>, 'asinh': <built-in function asinh>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'atanh': <built-in function atanh>, 'ceil': <built-in function ceil>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'cosh': <built-in function cosh>, 'degrees': <built-in function degrees>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'exp': <built-in function exp>, 'expm1': <built-in function expm1>, 'fabs': <built-in function fabs>, 'factorial': <built-in function factorial>, 'floor': <built-in function floor>, 'fmod': <built-in function fmod>, 'frexp': <built-in function frexp>, 'fsum': <built-in function fsum>, 'gamma': <built-in function gamma>, 'gcd': <built-in function gcd>, 'hypot': <built-in function hypot>, 'isclose': <built-in function isclose>, 'isfinite': <built-in function isfinite>, 'isinf': <built-in function isinf>, 'isnan': <built-in function isnan>, 'ldexp': <built-in function ldexp>, 'lgamma': <built-in function lgamma>, 'log': <built-in function log>, 'log1p': <built-in function log1p>, 'log10': <built-in function log10>, 'log2': <built-in function log2>, 'modf': <built-in function modf>, 'pow': <built-in function pow>, 'radians': <built-in function radians>, 'remainder': <built-in function remainder>, 'sin': <built-in function sin>, 'sinh': <built-in function sinh>, 'sqrt': <built-in function sqrt>, 'tan': <built-in function tan>, 'tanh': <built-in function tanh>, 'trunc': <built-in function trunc>, 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': <function square_root at 0x105b6a2f0>}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x105b11400>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/eval_example.py', '__cached__': None, 'acos': <built-in function acos>, 'acosh': <built-in function acosh>, 'asin': <built-in function asin>, 'asinh': <built-in function asinh>, 'atan': <built-in function atan>, 'atan2': <built-in function atan2>, 'atanh': <built-in function atanh>, 'ceil': <built-in function ceil>, 'copysign': <built-in function copysign>, 'cos': <built-in function cos>, 'cosh': <built-in function cosh>, 'degrees': <built-in function degrees>, 'erf': <built-in function erf>, 'erfc': <built-in function erfc>, 'exp': <built-in function exp>, 'expm1': <built-in function expm1>, 'fabs': <built-in function fabs>, 'factorial': <built-in function factorial>, 'floor': <built-in function floor>, 'fmod': <built-in function fmod>, 'frexp': <built-in function frexp>, 'fsum': <built-in function fsum>, 'gamma': <built-in function gamma>, 'gcd': <built-in function gcd>, 'hypot': <built-in function hypot>, 'isclose': <built-in function isclose>, 'isfinite': <built-in function isfinite>, 'isinf': <built-in function isinf>, 'isnan': <built-in function isnan>, 'ldexp': <built-in function ldexp>, 'lgamma': <built-in function lgamma>, 'log': <built-in function log>, 'log1p': <built-in function log1p>, 'log10': <built-in function log10>, 'log2': <built-in function log2>, 'modf': <built-in function modf>, 'pow': <built-in function pow>, 'radians': <built-in function radians>, 'remainder': <built-in function remainder>, 'sin': <built-in function sin>, 'sinh': <built-in function sinh>, 'sqrt': <built-in function sqrt>, 'tan': <built-in function tan>, 'tanh': <built-in function tanh>, 'trunc': <built-in function trunc>, 'pi': 3.141592653589793, 'e': 2.718281828459045, 'tau': 6.283185307179586, 'inf': inf, 'nan': nan, 'square_root': <function square_root at 0x105b6a2f0>}
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'square_root', 'tan', 'tanh', 'tau', 'trunc']

That’s a lot of functions that eval() will have access to. Most of them are from __builtins__ and math module.

eval()可以访问很多功能。 它们大多数来自__builtins__和math模块 。

Let’s see what happens when we specify globals value as empty dictionary in eval function.

让我们看看在eval函数中将globals值指定为空字典时会发生什么。

print(eval('dir()',{}))

Output:

输出:

['__builtins__']

So builtin methods are still available to eval function. If you want to limit access to only a few of the built-in methods, then you can specify its value for globals. For example, below code is allowing eval() function to execute only min built-in function.

因此,内置方法仍可用于eval函数。 如果只想限制对某些内置方法的访问,则可以为全局变量指定其值。 例如,下面的代码允许eval()函数仅执行min内置函数。

print(eval('min(1,2)',{'__builtins__':{'min': min}})) # 1

Let’s look at another example where I am providing locals value and disabling all the built-in functions access for eval().

让我们看另一个示例,在该示例中,我提供了locals值并禁用了eval()的所有内置函数访问。

y=5
print(eval('y+1',{'__builtins__': None}, {'y': y})) # 6

Let’s look at a final example where I am allowing access to only a few of the methods from math module. We are also mapping square_root to sqrt function for better human readability.

让我们看一个最后的示例,在该示例中,我仅允许访问math模块中的一些方法。 我们还将Square_root映射到sqrt函数,以提高人类可读性。

from math import *for l in range(1, 3):func = input("Enter Math Function to Evaluate.\nAllowed Functions are: square_root(x) and pow(x,y):\n")try:print(eval(func, {'square_root': sqrt, 'pow': pow}))except Exception as ex:print(ex)break
print('Done')

A sample output:

示例输出:

Enter Math Function to Evaluate.
Allowed Functions are: square_root(x) and pow(x,y):
square_root(16)
4.0
Enter Math Function to Evaluate.
Allowed Functions are: square_root(x) and pow(x,y):
log10(100)
name 'log10' is not defined
Done

I have not specified anything for builtin functions, so they will be available for eval() function.

我没有为内置函数指定任何内容,因此它们可用于eval()函数。

Below is another example run to show that built-in functions are available to be executed.

下面是另一个运行示例,显示可以执行内置函数。

Enter Math Function to Evaluate.
Allowed Functions are: square_root(x) and pow(x,y):
min(5,4)
4
Enter Math Function to Evaluate.
Allowed Functions are: square_root(x) and pow(x,y):
max(10,20)
20

摘要 (Summary)

Python eval() function is very powerful. Even though we have globals and locals variable to restrict access, they are not enough and workaround are available to harm your system. Read this article explaining why eval is dangerous. You shouldn’t use eval() function with untrusted user inputs.

Python eval()函数非常强大。 即使我们有globals和locals变量来限制访问,但它们还不够,并且可以使用变通办法来损害您的系统。 阅读这篇文章,解释为什么评估很危险 。 您不应将eval()函数用于不受信任的用户输入。

GitHub Repository.GitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/22504/python-eval-function

eval函数python

eval函数python_Python eval()函数相关推荐

  1. math ceil函数python_Python ceil函数

    Python ceil函数 最后更新于:2020-03-29 09:57:36 python ceil 内置函数和 int 函数有点类似,计算的结果都是得到一个整数,向上取整: 一.ceil函数简介 ...

  2. update函数python_python update函数

    在前一篇文章  python ChainMap中我们介绍了关于python内置函数 ChainMap的使用,ChainMap函数和update函数类似,都是对字典操作,也是将多个字典合并,那么问题来了 ...

  3. cycle函数python_Python执行函数的周期实现

    如下python代码是关于Python执行函数的周期实现,需要使用time模块及sched和os模块方法. 首先导入方法模块 #coding=utf-8 import time,sched,os 初始 ...

  4. 分割函数python_python strip() 函数和 split() 函数的详解及实例

    一直以来都分不清楚strip和split的功能,实际上strip是删除的意思:而split则是分割的意思.因此也表示了这两个功能是完全不一样的,strip可以删除字符串的某些字符,而split则是根据 ...

  5. 列表函数python_python 列表函数

    list函数: 功能:将字符创转化为列表,例: 列表基本函数: 1.元素赋值,例: 注意:通过list[0]= 'hel',如果原来位置上有值,会覆盖掉原来的. 2.分片操作 1)显示序列,例: 注意 ...

  6. fmod函数python_python fmod函数_Python numpy.fmod方法代码示例

    本文整理汇总了Python中numpy.fmod方法的典型用法代码示例.如果您正苦于以下问题:Python numpy.fmod方法的具体用法?Python numpy.fmod怎么用?Python ...

  7. pow函数python_python pow函数怎么用

    python中的pow函数的功能是计算x的y次幂.本篇文章将带大家一起了解一下,pow()函数在Python中的用法.感兴趣的朋友了解一下. 以下是 math 模块 pow() 方法的语法:impor ...

  8. JavaScript常用函数之Eval()使用

    eval() 功能:首先解释Javascript代码  然后执行它 用法:Eval(codeString) codeString是包含有javascript语句的字符串,在eval之后使用Javasc ...

  9. python中str和input_python中eval()函数和input()函数用法解析

    今天给大家讲解Python中eval()函数和input()函数的用法,希望通过实例的讲解之后大家能对这两个函数有更加深刻的理解. 1.eval()函数 eval(<字符串>)能够以Pyt ...

最新文章

  1. ajax调用上一个ajax,关于jquery:当频繁使用ajax请求调用函数时,如何在处理下一个请求之前等待上一个ajax请求完成?...
  2. 连年亏损的平安健康,能否成为中国版“联合健康”?
  3. swift inheritace 继承
  4. Python——PrettyTable
  5. 圣诞节海报设计还没开始?感受下合适的节日感PSD模板
  6. 20140711_类的继承、派生、ACE框架、指针的问题、系统的问题
  7. 科软-信息安全实验3-Rootkit劫持系统调用
  8. 问题六十八:着色模型(shading model)(1)——反射模型(reflection model)(2.2)——高光反射(specular reflection)
  9. 合理安排计算顺序避免溢出
  10. 中国 AI 天才养成计划:清华姚班和 100 个「张小龙」
  11. NSSM 注册PYTHON服务
  12. bit、Byte、KB、MB、GB互相转换的关系
  13. Linux wine系列——Ubuntu20.04安装wine教程 [2021.3]
  14. 案例:理想主义的猪与结果导向的猪
  15. ubutu16.04台式机没有声音处理方法
  16. 6月29日云栖精选夜读:Java、PHP、Python、JS 等开发者都如何绘制统计图
  17. 计算机视觉学习1-图像处理
  18. 微信开发 -- 二维码生成
  19. 公司太卷,研发3年经验裸辞,喜获字节/招银等6家大厂offer
  20. 汽车信息管理系统(C++实训)

热门文章

  1. [转载] numpy.argmin 使用
  2. [转载] pandas将Series变成键值对
  3. [转载] python笔记:4.1.2.1统计量_离散程度_方差和标准差
  4. pycharm——常用快捷键操作
  5. @Controller深入详解
  6. mvc图片上传到服务器
  7. 启动tomcat时遇到的问题
  8. delphi构造析构调用顺序
  9. PowerDesigner实用技巧小结(4)
  10. (二)OpenCV Mat常用属性和方法