gpt4 book ai didi

python - 调用 exec,尽管名称已定义,但出现 NameError

转载 作者:太空狗 更新时间:2023-10-30 02:52:36 26 4
gpt4 key购买 nike

我有一个名为 file.py 的文件,其中包含以下脚本:

def b():
print("b")
def proc():
print("this is main")
b()
proc()

我还有另一个名为 caller.py 的文件,其中包含以下脚本:

text = open('file.py').read()
exec(text)

当我运行它时,我得到了预期的输出:

this is main 

b

但是,如果我将 caller.py 更改为:

def main():
text = open('file.py').read()
exec(text)
main()

我收到以下错误:

this is main
Traceback (most recent call last):
File "./caller.py", line 7, in <module>
main()
File "./caller.py", line 5, in main
exec(text)
File "<string>", line 10, in <module>
File "<string>", line 8, in main
NameError: global name 'b' is not defined

函数 b() 是如何丢失的?在我看来,我没有违反任何范围规则。我需要制作类似于 caller.py 的第二个版本的东西。

最佳答案

exec(text) 在当前范围内执行 text,但修改该范围(如 def b 通过隐含赋值所做的那样)是未定义。

修复很简单:

def main():
text = open('file.py').read()
exec(text, {})

这会导致 text 在一个空的 global 作用域中运行(使用默认的 __builtins 对象进行扩充),这与常规的方式相同Python 文件。

有关详细信息,请参阅 exec documentation .它还警告修改默认本地范围(当不指定除 text 之外的任何参数时暗示)是不合理的:

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

关于python - 调用 exec,尽管名称已定义,但出现 NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52673265/

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