Python 3 - 需要从 exec() 到 return 值

Python 3 - need from exec() to return values

exec() 我有一个小问题。我有来自 Kivy GUI 的字符串,我需要执行它并存储已执行代码的值。

class gui(BoxLayout):
    def proces(self):
        t = threading.Thread(target=self.graf)
        t.daemon = True
        t.start()

    def graph(self):

        CodeInput=self.ids.codas
        Code=CodeInput.text
        x, y = [], []
        exec(Code)
        print(x,y) # empty list prints
        # then x y will serve for plotting a graph

这是一个字符串里面的 'Code':

def values():
    x=np.linspace(0,3.14,100)
    y=np.sin(x)
    print(x) # of course works
    return x,y
x,y=values()

一切正常,除了我无法从 exec(Code) 获取值 x、y。它就像 exec() 是完全独立的操作,可以启动但不能进入。

您应该使用本地名称空间调用 exec

loc = {}
exec(Code, {}, loc)
x = loc['x']
y = loc['y']