【问题标题】:Exec can't access variables in it's parent environmentExec 无法访问其父环境中的变量
【发布时间】:2019-09-30 08:20:03
【问题描述】:

我的朋友让我构建一个可以在 for 循环中执行代码的函数,所以我正在这样做,我在同一个文件中使用 exec,我声明了一个变量 name,现在当我访问 name来自 exec,上面写着 NameError: name 'name' is not defined

这个东西在多个文件中,一个运行一切,一个包含所有函数,一个调用所有函数

我尝试在 exec 中定义变量,并且确定它可以工作。 我试过在functions.py(包含每个函数的文件)文件中访问变量,它也可以工作。

我已经尝试合并functions.pytest.py(使用exec的文件),然后直接通过python运行它并且它工作

我的functions.py 文件

def forloop(current, maximum, code):
    for x in range(current, maximum):
        exec(str(code), globals())

我的'test.py'(这是我调用函数的地方)

from functions import *
name = 'Ameer'
forloop(1,3,"""
echo(name)
""")

而且,我正在通过我的 'runner.py' 中的另一个 exec 运行它

from functions import *
file = open('test.py', "r+")
content = file.read()
exec(content)

现在,当它被定义时,它给了我一个错误说NameError: name 'name' is not defined。请大家帮我解决这个问题

【问题讨论】:

  • 您可能根本不应该使用 exec,您能解释一下您更广泛的用例吗?

标签: python python-3.x variables exec


【解决方案1】:

你需要使用forloop被调用的地方的变量。

import inspect


def forloop(current, maximum, code):
    frame = inspect.currentframe().f_back
    for x in range(current, maximum):
        exec(str(code), frame.f_globals, frame.f_locals)

【讨论】:

  • 兄弟,谢谢,它有效,我想接受你的回答,但是,请告诉我为什么它有效,因为我最不想做的就是在我的项目中添加我不明白的代码
猜你喜欢
  • 2014-02-11
  • 2018-03-17
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 2018-08-10
  • 2012-01-30
  • 2020-12-02
相关资源
最近更新 更多