使用Jython来实现:
py文件内容:
代码:
public static void main(String[] args) {
//配置
Properties props = new Properties();
props.put("python.home", "path to the Lib folder");
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
//使用
PythonInterpreter interpreter = new PythonInterpreter();
// interpreter.exec("import sys");
// interpreter.exec("sys.path.append('/usr/local/python3/lib/python3.6/site-packages')");
interpreter.execfile("D:/a/py/testpy.py");//文件绝对路径
PyFunction func = (PyFunction) interpreter.get("process", PyFunction.class);//调用的函数名
PyObject pyobj = func.__call__(new PyInteger(1),new PyInteger(2));//参数,利用重载
Logs.get().info("py返回结果------:" + pyobj.toString());
}
在这里的配置信息如果不加上的话会报错,报错如下:
问题:
在这里说明一下因为Jython现在最新的版本貌似只是2.7.2版本,所以python3的一些函数他是不支持的,会出现“ModuleNotFoundError: No module named ‘XXX’ ”这个问题
所以我们在这里需要在java中手动指定一下py的sys,也就是注释掉的这两行
interpreter.exec("import sys");
interpreter.exec("sys.path.append('/usr/local/python3/lib/python3.6/site-packages')");//这个路径是py使用的配置路径
再推荐一下别的调用py的技术,
py4j
当然使用java自带的也是可以的,简单的一个例子:
Process process = Runtime.getRuntime().exec("python D:/a/py/testpy.py");
process.destroy();//销毁进程
这个自带的就是相当于java打开小黑框进行操作,所以最后要把它关闭,还有这里还有异常需要捕获(⊙o⊙)。