Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

python - How to return value from exec in function?

I try:

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

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

its return 'TEST12344'[:2]

How to return value from exec in function

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...