前言
Jython(原 JPython)敞咧,是一個用 Java 語言寫的 Python 解釋器。由于python語法簡潔,寫起來快遣钳,而且目前有很多現(xiàn)成的算法庫彤避,所以別的語言也想坐享其成傅物,Java也不例外,如果能直接調(diào)用這些庫琉预,那對Java的普及將更為有力董饰。
- 需要注意的是目前Jython只支持python2.x,以下給出一個case案例。
python
Test.py
def wdd(a, b):
return a + b
java
依賴
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
JpythonUtil.java
import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class JpythonUtil {
public static String runPythonMethod(PythonInterpreter interpreter, String handlerFunc, String fieldVal) {
PyFunction func = (PyFunction)interpreter.get(handlerFunc, PyFunction.class);
PyObject pyObject = func.__call__(Py.java2py(fieldVal));
if (pyObject==null) {
return null;
} else if (pyObject.toString().equals("null")) {
return null;
} else if (pyObject.toString().equals("None")) {
return null;
}else {
return pyObject.toString();
}
}
public static String runPythonMethod(PythonInterpreter interpreter, String handlerFunc, Integer param1, Integer param2) {
PyFunction func = (PyFunction)interpreter.get(handlerFunc, PyFunction.class);
PyObject pyObject = func.__call__(Py.java2py(param1), Py.java2py(param2));
if (pyObject==null) {
return null;
} else if (pyObject.toString().equals("null")) {
return null;
} else if (pyObject.toString().equals("None")) {
return null;
}else {
return pyObject.toString();
}
}
public static PythonInterpreter initPythonEnv(String pyProjectDir, String pyDependDir, String pyFile) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys");
interpreter.exec("sys.path.append(\"" + pyProjectDir + "\")");
interpreter.exec("sys.path.append(\"" + pyDependDir + "\")");
interpreter.execfile(pyFile);
return interpreter;
}
public static void closePythonEnv(PythonInterpreter interpreter) {
interpreter.cleanup();
interpreter.close();
}
public static void main(String[] args) {
String pyProjectDir = "/Users/dengpengfei/PycharmProjects/PySpark";
String pyDependDir = "/Users/dengpengfei/PycharmProjects/Venv2.7/lib/python2.7/site-packages";
String pyFile = "/Users/dengpengfei/PycharmProjects/PySpark/Test.py";
PythonInterpreter interpreter = initPythonEnv(pyProjectDir, pyDependDir, pyFile);
String line = runPythonMethod(interpreter, "wdd", 1, 1);
System.out.println(line);
}
}
結(jié)
目前這種java調(diào)用python的可行性是沒問題的卒暂,但是隨著python3.x的廣泛使用啄栓,Jython的迭代還需加快呀。