Created
August 10, 2011 19:08
-
-
Save bricef/1137838 to your computer and use it in GitHub Desktop.
Using Python from Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.FileReader; | |
import java.io.InputStreamReader; | |
import org.python.core.PyObject; | |
import org.python.util.PythonInterpreter; | |
public class Simple { | |
public static void main(String[] args) { | |
PythonInterpreter python = new PythonInterpreter(); | |
/* | |
* The following two lines make it work. | |
*/ | |
python.exec("import sys"); | |
python.exec("sys.executable=\"\""); | |
//exec the file in the interpreter | |
python.execfile("./test.py"); | |
//print the interpreter's namespace | |
//System.out.println(python.getLocals()); | |
//recover an object from the namespace | |
PyObject foo = python.get("anInstance"); | |
//invoke a method on the recovered object | |
PyObject bar = foo.invoke("mySimpleMethod"); | |
System.out.println(bar); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment