摘要
在日常的开发过程中我们经常遇到的java调用python的脚本,所以在本博文中我将为大家展示java项目的dokcer调用python服务的docker项目,同样在java调用其他语言的时候也是同样的一个道理。以下的例子仅仅工大家参考。
项目结构
项目代码
package com.xjl.javatopython.function;
import org.python.core.*;
import org.python.util.PythonInterpreter;
/**
* @Classname JavaCallPython
* @Description TODO
* @Date 2021/9/30 7:31
* @Created by xjl
*/
public class JavaCallPython {
//解释器
private PythonInterpreter pythonInterpreter;
public PythonInterpreter getPythonInterpreter(String pythonfile) {
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.execfile(pythonfile);
return pythonInterpreter;
}
public void setPythonInterpreter(PythonInterpreter pythonInterpreter) {
this.pythonInterpreter = pythonInterpreter;
}
/**
* @description TODO 调用py文件里的属性
* @param: interpreter
* @param: path
* @date: 2021/9/30 6:29
* @return: void
* @author: xjl
*/
public void calllpython_name(PythonInterpreter interpreter) {
PyObject xyzobj = interpreter.get("xyz");
System.out.println("xyz=" + xyzobj);
PyObject abcobj = interpreter.get("abc");
System.out.println("abc=" + abcobj);
interpreter.set("newstr", "newString");//手动添加newstr变量
System.out.println("newstr=" + interpreter.get("newstr"));
interpreter.exec("print('='*50)");
}
/**
* @description TODO 调用python的函数
* @param: interpreter
* @param: path
* @date: 2021/9/30 6:30
* @return: void
* @author: xjl
*/
public void calllpython_function(PythonInterpreter interpreter) {
PyFunction funStr = interpreter.get("func_str", PyFunction.class);
System.out.println(funStr.__call__().__tojava__(PyString.class));
System.out.println(funStr.__call__());
PyFunction funList = interpreter.get("func_list", PyFunction.class);
PyList list = (PyList) funList.__call__().__tojava__(PyList.class);
System.out.println(list);
System.out.println(list.get(2));
PyFunction funDict = interpreter.get("func_dict", PyFunction.class);
PyDictionary dict = (PyDictionary) funDict.__call__().__tojava__(PyDictionary.class);
System.out.println(dict);
System.out.println(dict.get(2));
}
public static void main(String[] args) {
String python_path = "Java_To_Python/src/main/resources/scripts/test.py";
JavaCallPython testCallPython_jython = new JavaCallPython();
PythonInterpreter pythonInterpreter = testCallPython_jython.getPythonInterpreter(python_path);
testCallPython_jython.calllpython_name(pythonInterpreter);
testCallPython_jython.calllpython_function(pythonInterpreter);
}
}
?
|