背景
在开发一个项目的某个功能的时候,需要要用一个算法模型(甲方已提供python脚本),但后端用是java来写的。开始想用java来重写,但因为涉及到某些库,java不怎么支持。后来没办法,就尝试用java来调用python脚本。结果没想到还真可以。
引入版本
<!--调用python使用-->
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
核心调用方法
#脚本我放在了config文件夹下,可以灵活更改脚本内容。
public static String resolvePythonScriptPath(String filename) {
File file = new File("./config/" + filename);
return file.getAbsolutePath();
}
public static List<String> readProcessOutput(InputStream inputStream) throws IOException {
try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
return output.lines()
.collect(Collectors.toList());
}
}
python脚本
因为涉及到甲方的隐私,我就随便写了给脚本。
##!/usr/bin/python
# -*- coding: utf-8 -*-
if __name__ == "__main__":
print(1+2)
调用案例
public static void main(String[] args) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("python",
resolvePythonScriptPath("algorithm.py"));
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
List<String> results = readProcessOutput(process.getInputStream());
System.out.println("results = " + results);
}
成功截图
学习java群
java交流群:868794080