0

「somefunc」という関数があります:

def somefunc():
    return "ok"

そして、次のような exec() で実行したかった:

exec("somefunc()")

それはうまくいきます。しかし、問題は、戻り値「ok」を取得できないことです。私はこれをやろうとしました:

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

しかし、私は何も持っていません。戻り値を取得するにはどうすればよいですか?

4

2 に答える 2

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.

于 2020-06-07T10:00:36.837 に答える