如何从函数中的 exec 中获取 return 值?

How to return value from exec in function?

我试试:

def test(w,sli):
    s = "'{0}'{1}".format(w,sli)
    exec(s)
    return s

print test("TEST12344","[:2]")

其return'TEST12344'[:2]

如何return函数中exec的值

exec() 不只是计算表达式,它还执行代码。您必须在 exec() 调用 .

中保存引用
def test(w, sli):
    exec('s = "{}"{}'.format(w, sli))
    return s

如果您只想计算表达式,请使用 eval(),并保存对返回值的引用:

def test(w,sli):
    s = "'{0}'{1}".format(w,sli)
    s = eval(s)
    return s

但是,我建议尽可能避免在任何实际代码中使用 exec()eval()。如果您使用它,请确保您有充分的理由这样做。

考虑运行以下代码。

code = """
def func():
    print("std out")
    return "expr out"
func()
"""

在 Python 控制台上

如果您在 python 控制台上 运行 func(),输出将类似于:

>>> def func():
...     print("std out")
...     return "expr out"
...
>>> func()
std out
'expr out'

与执行

>>> exec(code)
std out
>>> print(exec(code))
std out
None

如您所见,return 是 None。

带评估

>>> eval(code)

会产生错误。

所以我做了我的 exec_with_return()

import ast
import copy
def convertExpr2Expression(Expr):
        Expr.lineno = 0
        Expr.col_offset = 0
        result = ast.Expression(Expr.value, lineno=0, col_offset = 0)

        return result
def exec_with_return(code):
    code_ast = ast.parse(code)

    init_ast = copy.deepcopy(code_ast)
    init_ast.body = code_ast.body[:-1]

    last_ast = copy.deepcopy(code_ast)
    last_ast.body = code_ast.body[-1:]

    exec(compile(init_ast, "<ast>", "exec"), globals())
    if type(last_ast.body[0]) == ast.Expr:
        return eval(compile(convertExpr2Expression(last_ast.body[0]), "<ast>", "eval"),globals())
    else:
        exec(compile(last_ast, "<ast>", "exec"),globals())

exec_with_return(code)

我在Python2020年3.8的发现

在求值逻辑中:

a="1+99"
a=eval(a)
print(a) # output: 100

在执行逻辑中

exec ("a=33+110")
print(a) #output 143