执行名称 "templet_1h" 未定义

exec name "templet_1h" is not defined

我正在尝试使用 exec 和 eval 函数编写代码,以从 numpy .npz 文件中读取变量列表。

当我 运行 代码未将其定义为函数 def 时,代码有效。但是,当我 运行 代码作为函数时,即 read_file_npz("file_address") , python 3.7 不断弹出消息说 templet_1h 未定义.

def read_file_npz(file_names_2):
    import numpy as np
    Delete_elements=["arr_0"]

    evaluate_1= "templet_1h=np.load(\"./" +file_names_2+ ".npz\")";
    exec(evaluate_1)

    for i in (templet_1h.files):
        if not ( (i in Delete_elements) ):
            evaluate_2="global "+i;
            exec(evaluate_2)

            evaluate_2= i+"="+"templet_1h[\"" + i + "\"]";
            exec(evaluate_2)

警告有什么问题,如何修改?

我试图在代码之前将 templet_1h 清除为 list(),但随后警告变为 .files had no ... towards lists,就好像 evaluate_1 从来没有 运行.

使用 exec(evaluate_1, globals()) 来为 exec 中的全局变量和局部变量使用全局字典。

代码将定义的变量添加到全局字典中。无法将其添加为函数的局部变量。