0

I have a function called 'somefunc' :

def somefunc():
    return "ok"

And i wanted to run it with exec() like :

exec("somefunc()")

That works great. But the problem is, i can't get the returned value "ok". I've tried to do this:

a = exec("somefunc()")
print (a)

But i've got nothing. how can i get the returned value?

2
  • exec("a = somefunc()") stackoverflow.com/questions/23917776/… Commented Jun 7, 2020 at 10:00
  • 1
    You could create a dictionary of functions keyed by their names if you need to dynamically invoke functions by a string variable. exec solutions are seldom optimal. Commented Jun 7, 2020 at 10:11

2 Answers 2

3

If you want to use exactly the exec() function, the answer by @Leo Arad is okay.

But I think you misunderstood exec() and eval() functions. If so, then:

a = exec("somefunc()")
print (a)

It'd work when you'd use eval():

a = eval("somefunc()")
print(a)
Sign up to request clarification or add additional context in comments.

Comments

2

You need to store the function output straight to a

def somefunc():
    return "ok"

exec("a = somefunc()")
print(a)

Output

ok

exec() is executing the statement that you provide it as text so in this case, the exec will store the return value the a variable.

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.