eval函数python_Python eval()函数

eval函数python_Python eval()函数eval 函数 pythonPython functionisus Pythoneval 函数用于将表达式字符串解析为 python 表达式 然后执行它 Pythoneval 函数 Pythoneval function

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 = 1 print(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__': 
   
     , '__file__': '/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/eval_example.py', '__cached__': None, 'acos': 
    
      , 'acosh': 
     
       , 'asin': 
      
        , 'asinh': 
       
         , 'atan': 
        
          , 'atan2': 
         
           , 'atanh': 
          
            , 'ceil': 
           
             , 'copysign': 
            
              , 'cos': 
             
               , 'cosh': 
              
                , 'degrees': 
               
                 , 'erf': 
                
                  , 'erfc': 
                 
                   , 'exp': 
                  
                    , 'expm1': 
                   
                     , 'fabs': 
                    
                      , 'factorial': 
                     
                       , 'floor': 
                      
                        , 'fmod': 
                       
                         , 'frexp': 
                        
                          , 'fsum': 
                         
                           , 'gamma': 
                          
                            , 'gcd': 
                           
                             , 'hypot': 
                            
                              , 'isclose': 
                             
                               , 'isfinite': 
                              
                                , 'isinf': 
                               
                                 , 'isnan': 
                                
                                  , 'ldexp': 
                                 
                                   , 'lgamma': 
                                  
                                    , 'log': 
                                   
                                     , 'log1p': 
                                    
                                      , 'log10': 
                                     
                                       , 'log2': 
                                      
                                        , 'modf': 
                                       
                                         , 'pow': 
                                        
                                          , 'radians': 
                                         
                                           , 'remainder': 
                                          
                                            , 'sin': 
                                           
                                             , 'sinh': 
                                            
                                              , 'sqrt': 
                                             
                                               , 'tan': 
                                              
                                                , 'tanh': 
                                               
                                                 , 'trunc': 
                                                
                                                  , 'pi': 3.9793, 'e': 2.9045, 'tau': 6.9586, 'inf': inf, 'nan': nan, 'square_root': 
                                                 
                                                   } {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x105b11400>, '__spec__': None, '__annotations__': {}, '__builtins__': 
                                                  
                                                    , '__file__': '/Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/eval_example.py', '__cached__': None, 'acos': 
                                                   
                                                     , 'acosh': 
                                                    
                                                      , 'asin': 
                                                     
                                                       , 'asinh': 
                                                      
                                                        , 'atan': 
                                                       
                                                         , 'atan2': 
                                                        
                                                          , 'atanh': 
                                                         
                                                           , 'ceil': 
                                                          
                                                            , 'copysign': 
                                                           
                                                             , 'cos': 
                                                            
                                                              , 'cosh': 
                                                             
                                                               , 'degrees': 
                                                              
                                                                , 'erf': 
                                                               
                                                                 , 'erfc': 
                                                                
                                                                  , 'exp': 
                                                                 
                                                                   , 'expm1': 
                                                                  
                                                                    , 'fabs': 
                                                                   
                                                                     , 'factorial': 
                                                                    
                                                                      , 'floor': 
                                                                     
                                                                       , 'fmod': 
                                                                      
                                                                        , 'frexp': 
                                                                       
                                                                         , 'fsum': 
                                                                        
                                                                          , 'gamma': 
                                                                         
                                                                           , 'gcd': 
                                                                          
                                                                            , 'hypot': 
                                                                           
                                                                             , 'isclose': 
                                                                            
                                                                              , 'isfinite': 
                                                                             
                                                                               , 'isinf': 
                                                                              
                                                                                , 'isnan': 
                                                                               
                                                                                 , 'ldexp': 
                                                                                
                                                                                  , 'lgamma': 
                                                                                 
                                                                                   , 'log': 
                                                                                  
                                                                                    , 'log1p': 
                                                                                   
                                                                                     , 'log10': 
                                                                                    
                                                                                      , 'log2': 
                                                                                     
                                                                                       , 'modf': 
                                                                                      
                                                                                        , 'pow': 
                                                                                       
                                                                                         , 'radians': 
                                                                                        
                                                                                          , 'remainder': 
                                                                                         
                                                                                           , 'sin': 
                                                                                          
                                                                                            , 'sinh': 
                                                                                           
                                                                                             , 'sqrt': 
                                                                                            
                                                                                              , 'tan': 
                                                                                             
                                                                                               , 'tanh': 
                                                                                              
                                                                                                , 'trunc': 
                                                                                               
                                                                                                 , 'pi': 3.9793, 'e': 2.9045, 'tau': 6.9586, 'inf': inf, 'nan': nan, 'square_root': 
                                                                                                
                                                                                                  } ['__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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/211467.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午10:21
下一篇 2026年3月18日 下午10:22


相关推荐

  • ExecuteNonQuery()返回值

    ExecuteNonQuery()返回值

    2021年9月25日
    48
  • S如何解决安卓DK无法下载Package问题

    S如何解决安卓DK无法下载Package问题

    2022年1月13日
    50
  • Android HandlerThread 详解

    Android HandlerThread 详解概述HandlerThread相信大家都比较熟悉了,从名字上看是一个带有Handler消息循环机制的一个线程,比一般的线程多了消息循环的机制,可以说是Handler+Thread的结合

    2022年6月30日
    26
  • django项目配置使用elasticsearch搜索引擎

    django项目配置使用elasticsearch搜索引擎Elasticsearc 简称 ES 是一个基于 Lucene 实现的开源 分布式 Restful 的全文本搜索引擎 此外 它还是一个分布式实时文档存储 其中每个文档的每个 field 均是被索引的数据 且可被搜索 也是一个带实时分析功能的分布式搜索引擎 能够扩展至数以百计的节点实时处理 PB 级的数据 基本组件索引 index 文档容器 换句话说 索引是具有类似属性的文档的集合 类似新华字典的索引检索页 里面包含了关键词与词条的对应关系 并记录词条的位置 索引名必须使用小写字母 搜索

    2025年8月4日
    6
  • 即梦AI测评:新手友好型创作神器,真有传说中那么神?

    即梦AI测评:新手友好型创作神器,真有传说中那么神?

    2026年3月12日
    5
  • 智慧小区_智慧社区便民服务平台

    智慧小区_智慧社区便民服务平台1.1智慧小区的概念人类已迈进了二十一世纪,我们赖以生存的整个社会正面临着新经济时代所带来的种种变革。互联网技术的发展和应用不仅改变着人们工作、商务的模式,更开始全面地改变人们生活的观念和方式,在我们熟悉的物质城市的身边已经迅速形成一个信息化、虚拟化或者说是数字化的“新城市”。在这个“新城市”中,可以通过网络进行在线购物、远程医疗;可以在电脑前学习课程;人们将生活在“数字家庭”、“数字社区”、“数字城市”之中。智慧小区就是以互联网为依托,运用物联网技术将家庭中的智慧家居系统、社区的物联系统和服务整合在一

    2022年10月18日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号