Think of running the following code.
code = """
def func():
print("std out")
return "expr out"
func()
"""
On Python Console
If you run func()
on the python console, the output would be something like:
>>> def func():
... print("std out")
... return "expr out"
...
>>> func()
std out
'expr out'
With exec
>>> exec(code)
std out
>>> print(exec(code))
std out
None
As you can see, the return is None.
With eval
>>> eval(code)
will produce Error.
So I Made My 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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…