Python exec()

exec() 方法执行一个动态创建的程序,该程序可以是字符串或代码对象。

示例

program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

# Output: Sum = 15

exec() 语法

exec() 的语法是

exec(object, globals, locals)

exec() 参数

exec() 方法接受三个参数

  • object - 字符串或代码对象
  • globals(可选)- 一个字典
  • locals(可选)- 一个映射对象(通常是字典)

exec() 返回值

exec() 方法不返回任何值。


示例 1:Python exec()

program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

输出

Sum = 15

在上面的示例中,我们将字符串对象 program 传递给 exec() 方法。

该方法执行对象方法中的 python 代码,并产生输出 Sum = 15


示例 2:exec() 使用单行程序输入

# get an entire program as input
program = input('Enter a program:')

# execute the program exec(program)

输出

Enter a program: [print(item) for item in [1, 2, 3]]
1
2
3

在上面的示例中,我们提供了代码;

print(item) for item in [1, 2, 3]

作为输入值。

在这里,我们使用 exec() 方法执行具有用户输入代码的 program 对象。

注意:当您将 exec() 方法与 OS 模块一起使用时,需要小心。这是因为当您在输入中使用 os.system('rm -rf *') 代码时,您可能会意外地更改和删除文件。


示例 3:exec() 使用多行输入程序

我们可以借助 \n 将多行输入程序传递给 exec() 方法。但我们首先需要使用 compile() 方法编译程序。

# get a multi-line program as input
program = input('Enter a program:')

# compile the program in execution mode b = compile(program, 'something', 'exec')
# execute the program exec(b)

输出

Enter a program:'a = 5\nb=10\nprint("Sum =", a+b)'
90

在上面的示例中,我们将一个多行程序作为参数传递给 exec() 方法。

但在此之前,我们需要使用 compile() 方法编译此程序。


示例 4:使用 exec() 检查可用代码

检查可以与 exec() 方法一起使用的方法和变量是一个好主意。您可以使用 dir() 方法来完成此操作。

# import all the methods from math library
from math import *

# check the usable methods exec('print(dir())')

输出

['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__name__', ….]

示例 5:在 exec() 中阻止不必要的方法和变量

大多数情况下,我们不需要 exec() 的所有方法和变量。

我们可以通过将可选的 globalslocals 参数传递给 exec() 方法来阻止这些不必要的方法和变量。

有关更多信息,请查看 locals()globals()

# import methods from the math library
from math import *

# use cbrt() method 
mycode='''a = cbrt(9)
print(a)'''

# empty dictionary (global parameter) to restrict the cbrt() method exec(mycode, {})

输出

NameError: name 'cbrt' is not defined

在上面的示例中,我们限制了在 exec() 中使用 cbrt() 方法,尽管我们导入了整个数学库。

这就是我们得到输出 NameError: name 'cbrt' is not defined 的原因。


示例 6:在 exec() 中使用必要的方法和变量

我们还可以使必要的方法和变量可与 exec() 方法一起使用。

为此,我们需要将 locals 字典传递给 exec()

from math import *

# set globals parameter to none
globalsParameter = {'__builtins__' : None}

# set locals parameter to take only print() and dir() localsParameter = {'print': print, 'dir': dir}
# print the accessible method directory exec('print(dir())', globalsParameter, localsParameter)

输出

['dir', 'print']

在上面的示例中,我们使用代码阻止了所有全局内置方法

globalsParameter = {'__builtins__' : None}

但是,我们允许两个方法——print()dir() 可以用代码执行

localsParameter = {'print': print, 'dir': dir}

最后,我们将 dir() 方法传递给 print() 方法,然后将其传递给 exec() 方法以打印可用方法的列表。

这里的 globalsParameterlocalsParameter 是可选参数,我们与 exec() 方法一起使用它们,只打印我们想要访问的方法。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战