2

I have a small problem with exec(). I have string from Kivy GUI which I need to execute and store values from the executed code.

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

This is a string inside the '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()

Everything WORKS except I cant get the values x,y from exec(Code). Its like exec() is totaly separate operation that can be started but cannot be entered.

0

1 Answer 1

13

You should call exec with a local namespace:

loc = {}
exec(Code, {}, loc)
x = loc['x']
y = loc['y']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.