Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 778
user7172 Avatar asked Oct 29 '15 08:10

user7172


People also ask

How do you return a value from a python exec?

What does exec return in Python? Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors. If there are no syntax errors, the parsed string is executed.

What does exec return in SQL?

PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued.

Does exec return anything?

The exec functions replace the current process image with a new process image. The new image is constructed from a regular, executable file called the new process image file. There is no return from a successful exec, because the calling process image is overlaid by the new process image.

What is exec () in Python?

exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.


1 Answers

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)
like image 75
Allosteric Avatar answered Oct 12 '22 01:10

Allosteric