Skip to content

Instantly share code, notes, and snippets.

@bricef
Created August 10, 2011 19:08
Show Gist options
  • Save bricef/1137838 to your computer and use it in GitHub Desktop.
Save bricef/1137838 to your computer and use it in GitHub Desktop.
Using Python from Java
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