Faqts : Computers : Programming : Languages : Python : Python and Other Languages : Connecting

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 15 people (53%) answered Yes
Recently 6 of 10 people (60%) answered Yes

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");
    }
}
-----------------------------------------------