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')
compile()in eval mode maybe?