Entry
How do I invoke Python code from Java?
Nov 7th, 2002 07:09
Michael Chermside,
Although other options exist, the simplest and best way to invoke
Python code from Java is to use Jython. Jython (http://www.jython.org/)
is a version of Python which is very nicely integrated with java.
Depending on what you want to do, there are more advanced techniques
available (see Jython documentation), but what follows is a simple java
class which invokes and executes some Python code, passing java
variables in and out:
------------- SimpleEmbedded.java -------------
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class SimpleEmbedded {
public static void main(String []args) throws PyException {
PythonInterpreter interp = new PythonInterpreter();
System.out.println("Hello, brave new world");
interp.exec("import sys");
interp.exec("print sys");
interp.set("a", new PyInteger(42));
interp.exec("print a");
interp.exec("x = 2+2");
PyObject x = interp.get("x");
System.out.println("x: "+x);
System.out.println("Goodbye, cruel world");
}
}
-----------------------------------------------