gpt4 book ai didi

python - 为什么我使用 exec() 会得到 "NameError: name is not defined"?

转载 作者:行者123 更新时间:2023-12-01 08:18:32 26 4
gpt4 key购买 nike

当我在控制台(PyCharm 中)中尝试此代码时:

exec("import random")
exec("def f():\n\treturn random.randint(0, 10), random.randint(0, 10)")
locals()['f']()

效果很好。但是当我尝试在程序中执行完全相同的操作时,它不起作用,并且出现异常

NameError: name 'random' is not defined.

我发现这段代码不会引发错误:

exec("import random", globals(), globals())
exec("def f():\n\treturn random.randint(0, 10), random.randint(0, 10)", globals(), globals())
globals()['f']()

但我不明白为什么。

发生什么事了?

最佳答案

您在程序中没有做“完全相同”的事情。将该确切代码逐字复制到文件中并作为 Python 脚本运行,效果很好(尽管没有可见的结果)。

我认为你实际上可能在做的是这样的:

def import_stuff():
exec("import random")

def do_stuff():
import_stuff()
exec("def f():\n\treturn random.randint(0, 10), random.randint(0, 10)")
locals()['f']()

do_stuff()

上面的代码确实会导致您问题中提到的 NameError 异常,因为(引用 docs ),

In all cases, if the optional parts are omitted, the code is executed in the current scope.

由于上面的代码将 random 导入到 import_stuff() 的本地范围内,因此它对 do_stuff() 不可见。

事实上,上面的代码在行为上与以下代码相同:

def import_stuff():
import random

def do_stuff():
import_stuff()
def f():
return random.randint(0, 10), random.randint(0, 10)
f()

do_stuff()

…出于同样的原因,它也失败了。

假设这是您的真实代码中实际发生的情况,则通过将 globals(), globals() 参数添加到 exec() 来修改您的问题中的版本会起作用,因为这样你就显式地将random导入到全局范围内,所有东西都可以看到它。

关于python - 为什么我使用 exec() 会得到 "NameError: name is not defined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54840271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com