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?

Mr. lindroid
  • 162
  • 1
  • 12
  • exec("a = somefunc()") https://stackoverflow.com/questions/23917776/how-do-i-get-the-return-value-when-using-python-exec-on-the-code-object-of-a-fun – slick_reaper Jun 07 '20 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. – John Coleman Jun 07 '20 at 10:11

2 Answers2

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)
mchfrnc
  • 5,243
  • 5
  • 19
  • 37
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.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17