通过java 调用python 需要机器安装 jython,采用jython来中转,这里需要用到的包为 jython-standalone-2.7-b1.jar,可以直接在jython官网上下载,操作python过程:
1: 创建 PythonInterpreter 对象,通过该对象的exec() 可以直接执行python语言。
2: 调用python脚本参数
首先 通过 pythoninterpreter.execfile("***.py")
然后开始创建 PyFunction pf = pythoninterpreter.get("方法名",PyFunction.class)
最后 使用 pyObject 对象来接收方法值, 即 pf.__call__(new PySting(name));
例子:
package com.freemarker.main;
import java.math.BigDecimal;
import java.text.ParseException;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
import com.db.DBHelper;
public class Test {
public static void main(String[] args) throws ParseException {
PythonInterpreter interp = new PythonInterpreter();
System.out.println("Hello, brave new world");
interp.exec("import sys");
interp.exec("print sys");
interp.set("a", new PyInteger(42));
interp.exec("print a");
interp.exec("x = 2+2");
PyObject x = interp.get("x");
System.out.println("x: " + x);
System.out.println("Goodbye, cruel world!");
interp.execfile("tt.py");
PyFunction pFunction = interp.get("checkStr", PyFunction.class);// checkStr 方法名
String name = "guo"; // 这里配置python 方法的参数
PyObject pObject = pFunction.__call__(new PyString(name)); //前面用python的数据类型来包裹参数即可。
System.out.println(pObject.toString());
}
}