1.在pom中引用
jython-standalone
2.直接在java类中写python语句了,具体代码如下:
@Test
public void getPython() {
log.info("----开始-------");
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a=[5,2,3,9,4,0]; ");
interpreter.exec("print(sorted(a));"); //此处python语句是3.x版本的语法
interpreter.exec("print sorted(a);"); //此处是python语句是2.x版本的语法
}
3.java+python 传值和回值方法
//java+python 传值和回值方法
@Test
public void getPythonParam() throws Exception {
PythonInterpreter interpreter = new PythonInterpreter();
File f = new File(this.getClass().getResource("/").getPath());//获取类加载的根路径
File f2 = new File(this.getClass().getResource("").getPath());//获取当前类的所在工程路径;
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
log.info(f2+"---f---"+f);
String string = courseFile+"/src/main/resources/python/pyone.py";
log.info(courseFile+"/src/main/resources/python/pyone.py");
interpreter.execfile(string);
// 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
PyFunction pyFunction = interpreter.get("add", PyFunction.class);
int a = 5, b = 10;
//调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("the anwser is: " + pyobj);
}
# coding=utf-8
print("Do simple thing in Python")
print("输出中文")
def add(a,b):
return a + b



