python exec

Python exec() function provides support for dynamic code execution.

Python exec()函数提供了对动态代码执行的支持。

Python exec() (Python exec())

Python exec() function signature is:

Python exec()函数签名为:

exec(object, globals, locals)

object – It should be either a string or code object. If it’s string, then it’s parsed as a block of python statements and then execute it.

对象 –它应该是字符串或代码对象。 如果是字符串,则将其解析为python语句块,然后执行它。

globals – used to specify global functions available to be executed by exec() function. It must be a dictionary. If the __builtins__ is not defined, then all the built-in functions are available for exec function.

全局变量 –用于指定可由exec()函数执行的全局函数。 它必须是字典。 如果未定义__builtins__,则所有内置函数均可用于exec函数。

locals – used to specify local functions and variables available. It could be any mapping object. However, a dictionary is preferred for similarity with globals variable.

locals –用于指定可用的局部函数和变量。 它可以是任何映射对象。 但是,字典最好与全局变量相似。

Python exec() function returns None. So it can’t be used with return and yield statements.

Python exec()函数返回None。 因此,它不能与return和yield语句一起使用。

Python exec()与eval() (Python exec() vs eval())

Python exec() and eval() functions are very similar. Their usage and support for dynamic code execution is also very similar.

Python exec()和eval()函数非常相似。 它们的用法和对动态代码执行的支持也非常相似。

However, there is one major difference between exec() and eval() functions. Python exec() function doesn’t return anything whereas eval() function evaluates the expression and returns the value to the calling code.

但是,exec()和eval()函数之间有一个主要区别。 Python exec()函数不返回任何内容,而eval()函数对表达式求值并将其值返回给调用代码。

Python exec()示例 (Python exec() example)

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

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

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

Output:

输出:

True
3

Python exec()动态代码执行 (Python exec() dynamic code execution)

Let’s look at another example where the user will enter the code to be executed by our program.

让我们看另一个示例,其中用户将输入要由我们的程序执行的代码。

from math import *for l in range(1, 3):func = input("Enter Code Snippet to execute:\n")try:exec(func)except Exception as ex:print(ex)break
print('Done')

Example Output:

示例输出:

Enter Code Snippet to execute:
print(sqrt(16))
4.0
Enter Code Snippet to execute:
print(min(2,1))
1
Done

Notice that I am using sqrt() from math module, print() and min() are built-in functions.

请注意,我使用的是来自math模块的 sqrt(),print()和min()是内置函数。

Python exec()安全风险 (Python exec() security risks)

Since we can execute any code, there are security risks associated with exec() function. What if someone imports os module and issue os.system('rm -rf /') command. This will crash our system because all the files will be deleted. This is when globals and locals parameters come in handy to have restricted access.

由于我们可以执行任何代码,因此存在与exec()函数相关的安全风险。 如果有人导入os模块并发出os.system('rm -rf /')命令os.system('rm -rf /') 。 这将使我们的系统崩溃,因为所有文件都将被删除。 这是全局和局部参数派上用场以限制访问的时候。

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

Before we decide on the functions that should be available to exec(), it’s a good idea to get the list of available functions and modules using dir() function.

在决定exec()应该可用的功能之前,最好使用dir()函数获取可用功能和模块的列表。

from math import *def square_root(n):return sqrt(n)exec('print(dir())') # list of names in the current local scope

Output:

输出:

['__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, ranging from the builtins module, math module and our defined function square_root.

这有很多功能,包括内置模块,数学模块和我们定义的函数square_root。

Let’s see what happens if we provide globals value as an empty dictionary.

让我们看看如果将globals值提供为空字典会发生什么。

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

Output:

输出:

['__builtins__']

So built-in functions are available if globals don’t have a key for it. Let’s see how to specify access to only a few functions from the builtins module.

因此,如果全局变量没有键,则可以使用内置函数。 让我们看看如何指定仅从内建模块访问几个函数的权限。

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

Let’s look at another example where we will define both globals and locals parameter values.

让我们看另一个示例,在该示例中我们将定义全局参数和局部参数值。

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

Let’s look at a final example where we will provide access to only a few math module functions.

让我们看一个最后的示例,在该示例中,我们将仅提供对一些数学模块功能的访问。

from math import *for l in range(1, 3):func = input("Enter Code Snippet with Math Function to execute.\nFor Examples; print(squareRoot(x)) and print(pow(x,y)):\n")try:exec(func, {"squareRoot": sqrt, "pow": pow})except Exception as ex:print(ex)break
print('Done')

A Sample Output:

样本输出:

Enter Code Snippet with Math Function to execute.
For Examples; print(squareRoot(x)) and print(pow(x,y)):
print(squareRoot(100))
10.0
Enter Code Snippet with Math Function to execute.
For Examples; print(squareRoot(x)) and print(pow(x,y)):
print(max(2,4))
4
Done

We can specify a custom name to map with any function like we have defined squareRoot to be mapped to sqrt function.

我们可以指定一个自定义名称以使用任何函数进行映射,例如已经定义了squareRoot来映射到sqrt函数。

Notice that built-in functions are available because I haven’t explicitly excluded them. So a better way to define exec() is:

请注意,内置函数可用,因为我没有明确排除它们。 因此,定义exec()的更好方法是:

exec(func, {"squareRoot": sqrt, "pow": pow, "__builtins__": None, "print": print})

A sample output will be:

示例输出为:

Enter Code Snippet with Math Function to execute.
For Examples; print(squareRoot(x)) and print(pow(x,y)):
print(squareRoot(100))
10.0
Enter Code Snippet with Math Function to execute.
For Examples; print(squareRoot(x)) and print(pow(x,y)):
print(max(2,4))
'NoneType' object is not subscriptable
Done

Now the error is coming because max() function is not accessible to exec() function.

现在出现错误,因为exec()函数无法访问max()函数。

摘要 (Summary)

Just like eval(), python exec() function is very powerful. You shouldn’t allow any untrusted code to be executed using exec() as it can really harm your system.

就像eval()一样,python exec()函数非常强大。 您不应允许使用exec()执行任何不受信任的代码,因为它确实会损害您的系统。

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

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/22513/python-exec

python exec

python exec_Python exec()相关推荐

  1. python中eval函数调用_如何从Python exec()/eval()调用中获取结果?

    我想用Python编写一个工具,通过为每个模拟运行创建一个文件夹和一个带有一些运行特定参数的配置文件来准备模拟研究.在study/ study.conf run1 run.conf run2 run. ...

  2. 什么是Python的var_dump()的Python等价物? [重复]

    这个问题在这里已有答案: 是否有内置函数来打印对象的所有当前属性和值? 23个答案 在PHP中调试时,我经常发现在我的代码中简单地插入var_dump()以向我展示变量是什么,它的值是什么,以及它包含 ...

  3. PHP shell_exec()与exec()

    本文翻译自:PHP shell_exec() vs exec() I'm struggling to understand the difference between shell_exec() an ...

  4. Python中的“ @”(@)符号有什么作用?

    我正在看一些使用@符号的Python代码,但我不知道它的作用. 我也不知道要搜索什么,因为搜索Python文档时会出现,或者当包含@符号时Google不会返回相关结果. #1楼 此代码段: def d ...

  5. 如何使用Python numpy.where()方法

    In Python, we can use the numpy.where() function to select elements from a numpy array, based on a c ...

  6. Python字符串title()

    Python String title() Python字符串title() Python String title() function returns a title cased version ...

  7. Python字符串isdecimal()

    Python String isdecimal() function returns True if all the characters in the string are decimal char ...

  8. Python字符串isalnum()

    Python string isalnum() function returns True if it's made of alphanumeric characters only. A charac ...

  9. Python字符串count()

    Python String count() function returns the number of occurrences of a substring in the given string. ...

最新文章

  1. 网页轻松展示CV、NLP模型,连你老爸都会操作 | 斯坦福出品
  2. C 这些东西的内存管理
  3. Leetcode每日必刷题库第2题,如何实现两数相加?
  4. java面试笔试大汇总(一)
  5. 内网和外网的区别_无需服务器,树莓派使用内网穿透进行建站与维护
  6. 高级IO(文件的读写)——并发式IO的解决方案(解决多路阻塞式IO的方案)
  7. 用JavaScript实现网页图片等比例缩放
  8. Bootstrap3 表单支持的控件
  9. 高级音频降噪插件:Klevgrand Brusfri for Mac
  10. jvisualvm安装插件出现网络问题
  11. 酒店的月收入报表java_统计报表_宾馆明细收入报表
  12. Java工程师学习指南(完结篇)
  13. Multisim14仿真基本模拟电路之 10.5电压比较器及其应用电路的仿真实验与分析
  14. vsto 安装成功后打开office word不加载
  15. TVDI中线性拟合干湿边的步骤
  16. 流程型与离散型制造的区别【老外的分析】
  17. 主磁盘分区和逻辑磁盘分区的区别是什么?
  18. 只有那些不断充实自己的人,才有机会在往后的日子里持续地被雇用
  19. 如何使用国内代理ip?
  20. 市场上最受欢迎、消费者最爱吃的石锅鱼

热门文章

  1. 网上邻居不能正常访问的处理
  2. [转载] python eval序列化函数
  3. ATM系统之问题描述与词汇表
  4. [bzoj4763]雪辉[bzoj4812][Ynoi2017]由乃打扑克
  5. java并发编程(十)使用wait/notify/notifyAll实现线程间通信
  6. 在mysql的操作界面中,如何清屏幕
  7. Linux Kernel代码艺术——数组初始化
  8. 北京-波士顿-西雅图时间对照表
  9. STL vector简介
  10. 远程linux服务器中安装jupyter通过本地浏览器访问使用