前言
Jython(原 JPython),是一个用 Java 语言写的 Python 解释器。由于python语法简洁,写起来快,而且目前有很多现成的算法库,所以别的语言也想坐享其成,Java也不例外,如果能直接调用这些库,那对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);
}
}
结
目前这种java调用python的可行性是没问题的,但是随着python3.x的广泛使用,Jython的迭代还需加快呀。
网友评论