在 Python 中执行脚本

Vaibhav Vaibhav 2023年10月10日
  1. 在 Python 中执行 Python 脚本
  2. globalslocals 的使用
在 Python 中执行脚本

本文将讨论如何使用 Python 执行另一个 Python 脚本。

在 Python 中执行 Python 脚本

我们可以在 exec() 函数的帮助下使用 Python 执行 Python 脚本。exec() 函数是一个 Python 实用程序,它允许以字符串和字节格式动态执行 Python 代码。该函数接受三个参数,即

  • object:字符串或字节格式的 Python 代码
  • globals:这是一个可选参数。它是一个字典,包含全局函数和变量。
  • locals:这是一个可选参数。它是一个字典,包含局部函数和变量。

示例请参考以下代码。

file_name = "code.py"
content = open(file_name).read()
exec(content)

上面的代码首先在工作目录中打开一个名为 code.py 的文件,读取其内容,将其存储在名为 content 的变量中,然后将读取的内容传递给 exec() 功能。读取的内容是一些 Python 代码,exec() 方法将执行该 Python 代码。

如果我们有一些局部或全局变量,我们可以将它们存储在字典中并将它们传递给可执行脚本。然后脚本将能够利用这些变量并运行代码。请注意,如果我们在可执行脚本中使用一些未作为全局变量传递的函数,主程序将抛出异​​常。

以下代码描述了相同的内容。

from random import randint

code = "print(randint(1, 6))"
exec(code, {}, {})  # Empty globals and locals

输出:

Traceback (most recent call last):
  File "<string>", line 4, in <module>
File "<string>", line 1, in <module>
NameError: name 'randint' is not defined

globalslocals 未传递给 exec() 时,将自动处理(运行脚本)要求。Python 足够聪明,可以找出运行脚本所需的所有变量或函数。例如,以下代码将完美运行,不会出现任何错误。

from random import randint

code = "print(randint(1, 6))"
exec(code)  # No globals or locals passed

globalslocals 的使用

我们可以通过 globals 将自定义函数和导入函数传递给 exec() 函数,从而在可执行脚本中创建自定义函数和导入函数。如上所述,如果找不到这些依赖项,则会引发异常。

参考以下代码。在这里,我们将定义一个自定义函数并从 random 包中导入一个函数。然后这两个函数将通过 globals 参数传递给包含在字典中的 exec() 函数。

from random import randint


def get_my_age():
    return 19


globals = {"randint": randint, "get_my_age": get_my_age}

code = """
print(randint(1, 6))
print(get_my_age())
"""
exec(
    code,
    globals,
)

输出:

5 # It can be any number between 1 and 6, both inclusive
19

现在,这些函数已通过 globals 参数传递。我们也可以通过本地人传递它们。由于 exec 函数不接受关键字参数,我们必须为 globals 传递一个空字典,并传出 locals

from random import randint


def get_my_age():
    return 19


locals = {"randint": randint, "get_my_age": get_my_age}

code = """
print(randint(1, 6))
print(get_my_age())
"""
exec(code, {}, locals)

输出:

2 # It can be any number between 1 and 6, both inclusive
19
作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.