java代码
package com;
import org.python.core.PyFunction;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class CallPythonInterpreter {
private static PyFunction pyFunction = null;
public static void main(String[] args) {
PyObject pyObject = callPython(new PyString("D:/Program/Python/videoRec.py"));
System.out.println(pyObject.asString());
}
public static PyObject callPython(PyObject... params) {
if (pyFunction == null) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("D:/Program/Python/videoRec.py");
// 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
pyFunction = interpreter.get("fun", PyFunction.class);
}
PyObject pyobj = pyFunction.__call__(params);
return pyobj;
}
}
python脚本
import sys
def fun(img):
print(img)
return (img)
if __name__ == '__main__':
img = sys.argv[1]
fun(img)
Maven依赖
<!-- https://mvnrepository.com/artifact/org.python/jython -->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.5.3</version>
</dependency>