exec name “templet_1h” is not defined

半城伤御伤魂 提交于 2019-12-14 04:05:32

问题


I'm trying to write a code with exec and eval function to read lists of variables from a numpy .npz file.

When I ran the code without defining it as a function def, the code worked. However, when I ran the code as a function, i.e. read_file_npz("file_address") , the python 3.7 kept pop up message saying that templet_1h was not defined.

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)

What's wrong with the warning and how to modify it?

I tried to declear templet_1h before the code as list(), but then the warning became .files had no ... towards lists, as if evaluate_1 was never ran.


回答1:


Use exec(evaluate_1, globals()) instead to use the global dictionary for global and local variables in exec.

The code adds the defined variable to the global dictionary. Adding it as local variable of a function is not possible.



来源:https://stackoverflow.com/questions/53798843/exec-name-templet-1h-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!