0

I am attempting to write an API in Python that will allow me to run arbitrary Python code. In particular, I would like to be able to call any function through the API and have the return value passed back to me. The use case is that I have a Python library from which I would like to call functions from Java. Jython only supports Python 2 and I would prefer not embed Python in C/C++ embedded in Java.

My first instinct is to use exec(), but exec() does not support returning values. E.g, exec('10+20') returns None. Is there a more elegant way to do this than writing the output to a variable within the exec() call? e.g. exec('a=10+20')

1
  • compile() in eval mode maybe? Commented Mar 17, 2023 at 21:34

1 Answer 1

0

My current solution is below, and it even seems to work, which is nice.

import ast

def execute_with_return(code: str):
    tree = ast.parse(code)
    return_expr = None
    if type(tree.body[-1]) == ast.Expr:
        return_expr = tree.body[-1]
        tree.body = tree.body[:-1]
    exec(ast.unparse(tree))
    if return_expr:
        return eval(ast.unparse(return_expr))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.