Search code examples
pythonpython-3.xfunctionpython-exec

How to get the returned value of a function, called by exec() in python?


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?


Solution

  • 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)